com.netflix.loadbalancer.reactive.LoadBalancerCommand Java Examples

The following examples show how to use com.netflix.loadbalancer.reactive.LoadBalancerCommand. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HttpPluginSink.java    From ffwd with Apache License 2.0 6 votes vote down vote up
@Override
public AsyncFuture<Void> sendBatches(final Collection<Batch> batches) {
    final List<Callable<AsyncFuture<Void>>> callables = new ArrayList<>();

    for (final Batch b : batches) {
        callables.add(() -> {
            final Observable<Void> observable = LoadBalancerCommand.<Void>builder()
                .withLoadBalancer(loadBalancer)
                .build()
                .submit(server -> toObservable(clientFactory.newClient(server).sendBatch(b)));

            return fromObservable(observable);
        });
    }

    return async.eventuallyCollect(callables, VOID_COLLECTOR, PARALLELISM);
}
 
Example #2
Source File: LoadBalancingHttpClient.java    From ribbon with Apache License 2.0 6 votes vote down vote up
protected LoadBalancingHttpClient(Builder<I, O> builder) {
    super(builder.lb, builder.config, new RequestSpecificRetryHandler(true, true, builder.retryHandler, null), builder.pipelineConfigurator, builder.poolCleanerScheduler);
    requestIdHeaderName = getProperty(IClientConfigKey.Keys.RequestIdHeaderName, null, null);
    requestIdProvider = (requestIdHeaderName != null) 
                      ? new HttpRequestIdProvider(requestIdHeaderName, RxContexts.DEFAULT_CORRELATOR)
                      : null;
    this.listeners = new CopyOnWriteArrayList<ExecutionListener<HttpClientRequest<I>, HttpClientResponse<O>>>(builder.listeners);
    defaultCommandBuilder = LoadBalancerCommand.<HttpClientResponse<O>>builder()
            .withLoadBalancerContext(lbContext)
            .withListeners(this.listeners)
            .withClientConfig(builder.config)
            .withRetryHandler(builder.retryHandler)
            .build();
    this.responseToErrorPolicy = builder.responseToErrorPolicy;
    this.backoffStrategy = builder.backoffStrategy;
}
 
Example #3
Source File: MyUDPClient.java    From ribbon with Apache License 2.0 6 votes vote down vote up
public Observable<DatagramPacket> submit(final String content) {
    return LoadBalancerCommand.<DatagramPacket>builder()
            .withLoadBalancerContext(lbContext)
            .build()
            .submit(new ServerOperation<DatagramPacket>() {
                @Override
                public Observable<DatagramPacket> call(Server server) {
                    RxClient<DatagramPacket, DatagramPacket> rxClient = getOrCreateRxClient(server);
                    return rxClient.connect().flatMap(new Func1<ObservableConnection<DatagramPacket, DatagramPacket>, Observable<? extends DatagramPacket>>() {
                        @Override
                        public Observable<? extends DatagramPacket> call(ObservableConnection<DatagramPacket, DatagramPacket> connection) {
                            connection.writeStringAndFlush(content);
                            return connection.getInput().timeout(10, TimeUnit.MILLISECONDS).take(1);
                        }
                    });
                }
            });
}
 
Example #4
Source File: RibbonPublisherClient.java    From feign-reactive with Apache License 2.0 5 votes vote down vote up
public RibbonPublisherClient(@Nullable LoadBalancerCommand<Object> loadBalancerCommand,
                             PublisherHttpClient publisherClient,
                             Type publisherType) {
    this.loadBalancerCommand = loadBalancerCommand;
    this.publisherClient = publisherClient;
    this.publisherType = publisherType;
}
 
Example #5
Source File: CloudReactiveFeign.java    From feign-reactive with Apache License 2.0 5 votes vote down vote up
public Builder<T> enableLoadBalancer(RetryHandler retryHandler){
    if(retryHandler.getMaxRetriesOnSameServer() > 0){
        logger.warn("Use retryWhen(ReactiveRetryPolicy retryPolicy) " +
                "as it allow to configure retry delays (backoff)");
    }
    return setLoadBalancerCommandFactory(serviceName ->
            LoadBalancerCommand.builder()
            .withLoadBalancer(ClientFactory.getNamedLoadBalancer(serviceName))
            .withRetryHandler(retryHandler)
            .build());
}
 
Example #6
Source File: ProxyController.java    From haven-platform with Apache License 2.0 5 votes vote down vote up
@Autowired
public ProxyController(HttpProxy httpProxy, SpringClientFactory springClientFactory) {
    this.httpProxy = httpProxy;

    RibbonLoadBalancerContext context = springClientFactory.getLoadBalancerContext(SERVICEID);
    IClientConfig clientConfig = springClientFactory.getClientConfig(SERVICEID);
    ILoadBalancer loadBalancer = springClientFactory.getLoadBalancer(SERVICEID);
    HttpClientLoadBalancerErrorHandler requestSpecificRetryHandler = getRequestSpecificRetryHandler(clientConfig);

    this.commandBuilder = LoadBalancerCommand.builder()
            .withRetryHandler(requestSpecificRetryHandler)
            .withLoadBalancerContext(context)
            .withClientConfig(clientConfig)
            .withLoadBalancer(loadBalancer);
}
 
Example #7
Source File: AbstractLoadBalancerAwareClient.java    From ribbon with Apache License 2.0 5 votes vote down vote up
protected LoadBalancerCommand<T> buildLoadBalancerCommand(final S request, final IClientConfig config) {
	RequestSpecificRetryHandler handler = getRequestSpecificRetryHandler(request, config);
	LoadBalancerCommand.Builder<T> builder = LoadBalancerCommand.<T>builder()
			.withLoadBalancerContext(this)
			.withRetryHandler(handler)
			.withLoadBalancerURI(request.getUri());
	customizeLoadBalancerCommandBuilder(request, config, builder);
	return builder.build();
}
 
Example #8
Source File: LoadBalancingHttpClient.java    From ribbon with Apache License 2.0 5 votes vote down vote up
/**
 * Subject an operation to run in the load balancer
 * 
 * @param request
 * @param errorHandler
 * @param requestConfig
 * @param rxClientConfig
 * @return
 */
private Observable<HttpClientResponse<O>> submit(final Server server, final HttpClientRequest<I> request, final RetryHandler errorHandler, final IClientConfig requestConfig, final ClientConfig rxClientConfig) {
    RetryHandler retryHandler = errorHandler;
    if (retryHandler == null) {
        retryHandler = getRequestRetryHandler(request, requestConfig);
    }
    
    final IClientConfig config = requestConfig == null ? DefaultClientConfigImpl.getEmptyConfig() : requestConfig;
    final ExecutionContext<HttpClientRequest<I>> context = new ExecutionContext<HttpClientRequest<I>>(request, config, this.getClientConfig(), retryHandler);
    
    Observable<HttpClientResponse<O>> result = submitToServerInURI(request, config, rxClientConfig, retryHandler, context);
    if (result == null) {
        LoadBalancerCommand<HttpClientResponse<O>> command;
        if (retryHandler != defaultRetryHandler) {
            // need to create new builder instead of the default one
            command = LoadBalancerCommand.<HttpClientResponse<O>>builder()
                    .withExecutionContext(context)
                    .withLoadBalancerContext(lbContext)
                    .withListeners(listeners)
                    .withClientConfig(this.getClientConfig())
                    .withRetryHandler(retryHandler)
                    .withServer(server)
                    .build();
        }
        else {
            command = defaultCommandBuilder;
        }
        
        result = command.submit(requestToOperation(request, getRxClientConfig(config, rxClientConfig)));
    }
    return result;
}
 
Example #9
Source File: LoadBalancingRxClient.java    From ribbon with Apache License 2.0 5 votes vote down vote up
@Override
public Observable<ObservableConnection<O, I>> connect() {
    return LoadBalancerCommand.<ObservableConnection<O, I>>builder()
            .withLoadBalancerContext(lbContext)
            .build()
            .submit(new ServerOperation<ObservableConnection<O, I>>() {
                @Override
                public Observable<ObservableConnection<O, I>> call(Server server) {
                    return getOrCreateRxClient(server).connect();            
                }                    
            });
}
 
Example #10
Source File: CloudReactiveFeign.java    From feign-reactive with Apache License 2.0 4 votes vote down vote up
public Builder<T> enableLoadBalancer(){
    return setLoadBalancerCommandFactory(serviceName ->
            LoadBalancerCommand.builder()
                    .withLoadBalancer(ClientFactory.getNamedLoadBalancer(serviceName))
                    .build());
}
 
Example #11
Source File: CloudReactiveFeign.java    From feign-reactive with Apache License 2.0 4 votes vote down vote up
public Builder<T> setLoadBalancerCommandFactory(
        Function<String, LoadBalancerCommand<Object>> loadBalancerCommandFactory) {
    this.loadBalancerCommandFactory = loadBalancerCommandFactory;
    return this;
}
 
Example #12
Source File: ServiceLoadBalancer.java    From TeaStore with Apache License 2.0 4 votes vote down vote up
private <T, R> R loadBalanceRESTOperation(String endpointURI,
   		Class<T> entityClass, Function<RESTClient<T>, R> operation)
   				throws NotFoundException, LoadBalancerTimeoutException {
   	R r = null;
   	loadBalancerModificationLock.readLock().lock();
   	try {
   		if (loadBalancer == null) {
       		LOG.warn("Load Balancer was not initialized for service: " + targetService.getServiceName()
       			+ ". Is Registry up?");
       		updateLoadBalancersForServiceUsingRegistry(targetService);
       	}
       	if (loadBalancer == null || loadBalancer.getAllServers().isEmpty()) {
       		LOG.warn("No Server registered for Service: " + targetService.getServiceName());
       	} else {
       		ServiceLoadBalancerResult<R> slbr = LoadBalancerCommand.<ServiceLoadBalancerResult<R>>builder()
                       .withLoadBalancer(loadBalancer)
                       .withRetryHandler(retryHandler)
                       .build()
                       .submit(server -> Observable.just(
                       		ServiceLoadBalancerResult.fromRESTOperation(
                       				(RESTClient<T>) getEndpointClientCollection(endpointURI, entityClass)
               				.getRESTClient(server), operation)
                       		))
					.onErrorReturn((Throwable e) -> {
						e.printStackTrace();
						return null;
					}).toBlocking().first();
       		if (slbr == null) {
       			throw new NullPointerException("ServiceLoadBalancerResult was null!");
       		}
       		if (slbr.getStatusCode() == Status.REQUEST_TIMEOUT.getStatusCode()) {
       			throw new LoadBalancerTimeoutException("Timout at endpoint: "
       					+ endpointURI + ", with target service: " + targetService.getServiceName(),
       					targetService);
       		} else if (slbr.getStatusCode() == Status.NOT_FOUND.getStatusCode() || slbr.getEntity() == null) {
       			throw new NotFoundException();
       		}
       		r = slbr.getEntity();
       	}
   	} finally {
   		loadBalancerModificationLock.readLock().unlock();
   	}
	return r;
}
 
Example #13
Source File: AbstractLoadBalancerAwareClient.java    From ribbon with Apache License 2.0 4 votes vote down vote up
protected void customizeLoadBalancerCommandBuilder(final S request, final IClientConfig config,
		final LoadBalancerCommand.Builder<T> builder) {
	// do nothing by default, give a chance to its derived class to customize the builder
}