com.netflix.client.RetryHandler Java Examples

The following examples show how to use com.netflix.client.RetryHandler. 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: LoadBalancerContext.java    From ribbon with Apache License 2.0 6 votes vote down vote up
/**
 * This is called after an error is thrown from the client
 * to update related stats.  
 */
protected void noteError(ServerStats stats, ClientRequest request, Throwable e, long responseTime) {
	if (stats == null) {
		return;
	}
    try {
        recordStats(stats, responseTime);
        RetryHandler errorHandler = getRetryHandler();
        if (errorHandler != null && e != null) {
            if (errorHandler.isCircuitTrippingException(e)) {
                stats.incrementSuccessiveConnectionFailureCount();                    
                stats.addToFailureCount();
            } else {
                stats.clearSuccessiveConnectionFailureCount();
            }
        }
    } catch (Exception ex) {
        logger.error("Error noting stats for client {}", clientName, ex);
    }            
}
 
Example #2
Source File: LoadBalancingRxClientWithPoolOptions.java    From ribbon with Apache License 2.0 6 votes vote down vote up
public LoadBalancingRxClientWithPoolOptions(ILoadBalancer lb, IClientConfig config,
        RetryHandler retryHandler,
        PipelineConfigurator<O, I> pipelineConfigurator, ScheduledExecutorService poolCleanerScheduler) {
    super(lb, config, retryHandler, pipelineConfigurator);
    poolEnabled = config.get(CommonClientConfigKey.EnableConnectionPool, 
            DefaultClientConfigImpl.DEFAULT_ENABLE_CONNECTION_POOL);
    if (poolEnabled) {
        this.poolCleanerScheduler = poolCleanerScheduler;
        int maxTotalConnections = config.get(IClientConfigKey.Keys.MaxTotalConnections,
                DefaultClientConfigImpl.DEFAULT_MAX_TOTAL_CONNECTIONS);
        int maxConnections = config.get(Keys.MaxConnectionsPerHost, DefaultClientConfigImpl.DEFAULT_MAX_CONNECTIONS_PER_HOST);
        MaxConnectionsBasedStrategy perHostStrategy = new DynamicPropertyBasedPoolStrategy(maxConnections,
                config.getClientName() + "." + config.getNameSpace() + "." + CommonClientConfigKey.MaxConnectionsPerHost);
        globalStrategy = new DynamicPropertyBasedPoolStrategy(maxTotalConnections, 
                config.getClientName() + "." + config.getNameSpace() + "." + CommonClientConfigKey.MaxTotalConnections);
        poolStrategy = new CompositePoolLimitDeterminationStrategy(perHostStrategy, globalStrategy);
        idleConnectionEvictionMills = config.get(Keys.ConnIdleEvictTimeMilliSeconds, DefaultClientConfigImpl.DEFAULT_CONNECTIONIDLE_TIME_IN_MSECS);
    }
}
 
Example #3
Source File: ExecutionContextTest.java    From ribbon with Apache License 2.0 6 votes vote down vote up
@Test
public void testSubContext() {
    ExecutionContext<String> context = new ExecutionContext<String>("hello", DefaultClientConfigImpl.getEmptyConfig(),
            DefaultClientConfigImpl.getClientConfigWithDefaultValues(), RetryHandler.DEFAULT);
    ExecutionContext<String> subContext1 = context.getChildContext("foo");
    ExecutionContext<String> subContext2 = context.getChildContext("bar");
    assertSame(context, context.getGlobalContext());
    context.put("dummy", "globalValue");
    context.put("dummy2", "globalValue");
    subContext1.put("dummy", "context1Value");
    subContext2.put("dummy", "context2Value");
    assertEquals("context1Value", subContext1.get("dummy"));
    assertEquals("context2Value", subContext2.get("dummy"));
    assertEquals("globalValue", subContext1.getGlobalContext().get("dummy"));
    assertNull(subContext1.get("dummy2"));
}
 
Example #4
Source File: LoadBalancerContext.java    From ribbon with Apache License 2.0 6 votes vote down vote up
/**
 * This is called after a response is received or an exception is thrown from the client
 * to update related stats.  
 */
public void noteRequestCompletion(ServerStats stats, Object response, Throwable e, long responseTime, RetryHandler errorHandler) {
	if (stats == null) {
		return;
	}
    try {
        recordStats(stats, responseTime);
        RetryHandler callErrorHandler = errorHandler == null ? getRetryHandler() : errorHandler;
        if (callErrorHandler != null && response != null) {
            stats.clearSuccessiveConnectionFailureCount();
        } else if (callErrorHandler != null && e != null) {
            if (callErrorHandler.isCircuitTrippingException(e)) {
                stats.incrementSuccessiveConnectionFailureCount();                    
                stats.addToFailureCount();
            } else {
                stats.clearSuccessiveConnectionFailureCount();
            }
        }
    } catch (Exception ex) {
        logger.error("Error noting stats for client {}", clientName, ex);
    }            
}
 
Example #5
Source File: TestExtensionsManager.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Test
public void testRuleClassName() {
  BeansHolder holder = new BeansHolder();
  List<ExtensionsFactory> extensionsFactories = new ArrayList<>();
  extensionsFactories.add(new RuleNameExtentionsFactory());
  extensionsFactories.add(new DefaultRetryExtensionsFactory());
  Deencapsulation.setField(holder, "extentionsFactories", extensionsFactories);
  holder.init();
  RetryHandler retryHandler = ExtensionsManager.createRetryHandler("mytest1");
  Assert.assertTrue(DefaultLoadBalancerRetryHandler.class.isInstance(retryHandler));
  Assert.assertFalse(retryHandler.isRetriableException(new InvocationException(400, "", ""), false));
  Assert.assertFalse(retryHandler.isRetriableException(new InvocationException(400, "", ""), true));
  Assert.assertTrue(retryHandler.isRetriableException(new InvocationException(503, "", ""), true));
  Assert.assertTrue(retryHandler.isRetriableException(new ConnectException(), false));
  Assert.assertTrue(retryHandler.isRetriableException(new ConnectException(), true));
  Assert.assertTrue(retryHandler.isRetriableException(new SocketTimeoutException(), false));
  Assert.assertTrue(retryHandler.isRetriableException(new SocketTimeoutException(), true));
  Assert.assertFalse(retryHandler.isRetriableException(new IOException(), true));
}
 
Example #6
Source File: LoadBalancingHttpClient.java    From ribbon with Apache License 2.0 5 votes vote down vote up
private RetryHandler getRequestRetryHandler(HttpClientRequest<?> request, IClientConfig requestConfig) {
    return new RequestSpecificRetryHandler(
            true, 
            request.getMethod().equals(HttpMethod.GET),     // Default only allows retrys for GET
            defaultRetryHandler, 
            requestConfig);
}
 
Example #7
Source File: RibbonTransport.java    From ribbon with Apache License 2.0 5 votes vote down vote up
public static <I, O> LoadBalancingHttpClient<I, O> newHttpClient(PipelineConfigurator<HttpClientResponse<O>, HttpClientRequest<I>> pipelineConfigurator,
                                                         ILoadBalancer loadBalancer, IClientConfig config, RetryHandler retryHandler,
                                                              List<ExecutionListener<HttpClientRequest<I>, HttpClientResponse<O>>> listeners) {
    return LoadBalancingHttpClient.<I, O>builder()
            .withLoadBalancer(loadBalancer)
            .withClientConfig(config)
            .withRetryHandler(retryHandler)
            .withPipelineConfigurator(pipelineConfigurator)
            .withPoolCleanerScheduler(poolCleanerScheduler)
            .withExecutorListeners(listeners)
            .build();
}
 
Example #8
Source File: RibbonTransport.java    From ribbon with Apache License 2.0 5 votes vote down vote up
public static <I, O> LoadBalancingHttpClient<I, O> newHttpClient(PipelineConfigurator<HttpClientResponse<O>, HttpClientRequest<I>> pipelineConfigurator,
        IClientConfig config, RetryHandler retryHandler) {
    return LoadBalancingHttpClient.<I, O>builder()
            .withClientConfig(config)
            .withRetryHandler(retryHandler)
            .withPipelineConfigurator(pipelineConfigurator)
            .withPoolCleanerScheduler(poolCleanerScheduler)
            .build();
}
 
Example #9
Source File: RibbonTransport.java    From ribbon with Apache License 2.0 5 votes vote down vote up
public static LoadBalancingHttpClient<ByteBuf, ByteBuf> newHttpClient(ILoadBalancer loadBalancer, IClientConfig config, RetryHandler retryHandler,
                                                              List<ExecutionListener<HttpClientRequest<ByteBuf>, HttpClientResponse<ByteBuf>>> listeners) {
    return LoadBalancingHttpClient.<ByteBuf, ByteBuf>builder()
            .withLoadBalancer(loadBalancer)
            .withClientConfig(config)
            .withRetryHandler(retryHandler)
            .withPipelineConfigurator(DEFAULT_HTTP_PIPELINE_CONFIGURATOR)
            .withPoolCleanerScheduler(poolCleanerScheduler)
            .withExecutorListeners(listeners)
            .build();
}
 
Example #10
Source File: LoadBalancingRxClient.java    From ribbon with Apache License 2.0 5 votes vote down vote up
public LoadBalancingRxClient(IClientConfig config, RetryHandler defaultRetryHandler, PipelineConfigurator<O, I> pipelineConfigurator) {
    this(LoadBalancerBuilder.newBuilder().withClientConfig(config).buildLoadBalancerFromConfigWithReflection(),
            config,
            defaultRetryHandler,
            pipelineConfigurator
            );
}
 
Example #11
Source File: LoadBalancerContext.java    From ribbon with Apache License 2.0 5 votes vote down vote up
/**
 * This is called after a response is received from the client
 * to update related stats.  
 */
protected void noteResponse(ServerStats stats, ClientRequest request, Object response, long responseTime) {
	if (stats == null) {
		return;
	}
    try {
        recordStats(stats, responseTime);
        RetryHandler errorHandler = getRetryHandler();
        if (errorHandler != null && response != null) {
            stats.clearSuccessiveConnectionFailureCount();
        } 
    } catch (Exception ex) {
        logger.error("Error noting stats for client {}", clientName, ex);
    }            
}
 
Example #12
Source File: RibbonTransport.java    From ribbon with Apache License 2.0 5 votes vote down vote up
public static LoadBalancingHttpClient<ByteBuf, ByteBuf> newHttpClient(ILoadBalancer loadBalancer, IClientConfig config, RetryHandler retryHandler) {
    return LoadBalancingHttpClient.<ByteBuf, ByteBuf>builder()
            .withLoadBalancer(loadBalancer)
            .withClientConfig(config)
            .withRetryHandler(retryHandler)
            .withPipelineConfigurator(DEFAULT_HTTP_PIPELINE_CONFIGURATOR)
            .withPoolCleanerScheduler(poolCleanerScheduler)
            .build();
}
 
Example #13
Source File: LoadBalancingRxClient.java    From ribbon with Apache License 2.0 5 votes vote down vote up
public LoadBalancingRxClient(ILoadBalancer lb, IClientConfig config, RetryHandler defaultRetryHandler, PipelineConfigurator<O, I> pipelineConfigurator) {
    this.rxClientCache = new ConcurrentHashMap<Server, T>();
    this.lbContext = new LoadBalancerContext(lb, config, defaultRetryHandler);
    this.defaultRetryHandler = defaultRetryHandler;
    this.pipelineConfigurator = pipelineConfigurator;
    this.clientConfig = config;
    this.listener = createListener(config.getClientName());
    
    eventSubject = new MetricEventsSubject<ClientMetricsEvent<?>>();
    boolean isSecure = getProperty(IClientConfigKey.Keys.IsSecure, null, false); 
    if (isSecure) {
        final URL trustStoreUrl = getResourceForOptionalProperty(CommonClientConfigKey.TrustStore);
        final URL keyStoreUrl = getResourceForOptionalProperty(CommonClientConfigKey.KeyStore);
        boolean isClientAuthRequired = clientConfig.get(IClientConfigKey.Keys.IsClientAuthRequired, false);
        if (    // if client auth is required, need both a truststore and a keystore to warrant configuring
                // if client is not is not required, we only need a keystore OR a truststore to warrant configuring
                (isClientAuthRequired && (trustStoreUrl != null && keyStoreUrl != null))
                ||
                (!isClientAuthRequired && (trustStoreUrl != null || keyStoreUrl != null))
                ) {

            try {
                sslContextFactory = new URLSslContextFactory(trustStoreUrl,
                        clientConfig.get(CommonClientConfigKey.TrustStorePassword),
                        keyStoreUrl,
                        clientConfig.get(CommonClientConfigKey.KeyStorePassword));

            } catch (ClientSslSocketFactoryException e) {
                throw new IllegalArgumentException("Unable to configure custom secure socket factory", e);
            }
        } else {
            sslContextFactory = null;
        }
    } else {
        sslContextFactory = null;
    }

    addLoadBalancerListener();
}
 
Example #14
Source File: LoadBalancingRxClientWithPoolOptions.java    From ribbon with Apache License 2.0 5 votes vote down vote up
public LoadBalancingRxClientWithPoolOptions(IClientConfig config,
        RetryHandler retryHandler,
        PipelineConfigurator<O, I> pipelineConfigurator, ScheduledExecutorService poolCleanerScheduler) {
    this(LoadBalancerBuilder.newBuilder().withClientConfig(config).buildDynamicServerListLoadBalancer(),
            config,
            retryHandler,
            pipelineConfigurator,
            poolCleanerScheduler);
}
 
Example #15
Source File: ExecutionContext.java    From ribbon with Apache License 2.0 5 votes vote down vote up
public ExecutionContext(T request, IClientConfig requestConfig, IClientConfig clientConfig, RetryHandler retryHandler) {
    this.request = request;
    this.requestConfig = requestConfig;
    this.clientConfig = clientConfig;
    this.context = new ConcurrentHashMap<>();
    this.subContexts = new ConcurrentHashMap<>();
    this.retryHandler = retryHandler;
}
 
Example #16
Source File: ExecutionContext.java    From ribbon with Apache License 2.0 5 votes vote down vote up
ExecutionContext(T request, IClientConfig requestConfig, IClientConfig clientConfig, RetryHandler retryHandler, ConcurrentHashMap<Object, ChildContext<T>> subContexts) {
    this.request = request;
    this.requestConfig = requestConfig;
    this.clientConfig = clientConfig;
    this.context = new ConcurrentHashMap<>();
    this.subContexts = subContexts;
    this.retryHandler = retryHandler;
}
 
Example #17
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 #18
Source File: ExtensionsManager.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
public static RetryHandler createRetryHandler(String microservice) {
  RetryHandler handler = null;
  for (ExtensionsFactory factory : extentionFactories) {
    if (factory.isSupport(Configuration.RETRY_HANDLER, Configuration.INSTANCE.getRetryHandler(microservice))) {
      handler = factory.createRetryHandler(Configuration.INSTANCE.getRetryHandler(microservice), microservice);
      break;
    }
  }

  // handler can not be null. handler will be created for each invocation.
  LOGGER.debug("Using retry handler {} for microservice {}.", handler.getClass().getName(), microservice);
  return handler;
}
 
Example #19
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 #20
Source File: RibbonTransport.java    From ribbon with Apache License 2.0 4 votes vote down vote up
public static <I, O> RxClient<I, O> newUdpClient(ILoadBalancer loadBalancer, PipelineConfigurator<O, I> pipelineConfigurator, 
        IClientConfig config, RetryHandler retryHandler) {
    return new LoadBalancingUdpClient<I, O>(loadBalancer, config, retryHandler, pipelineConfigurator);
}
 
Example #21
Source File: RibbonTransport.java    From ribbon with Apache License 2.0 4 votes vote down vote up
private static RetryHandler getDefaultHttpRetryHandlerWithConfig(IClientConfig config) {
    return new NettyHttpLoadBalancerErrorHandler(config);
}
 
Example #22
Source File: RibbonTransport.java    From ribbon with Apache License 2.0 4 votes vote down vote up
private static RetryHandler getDefaultRetryHandlerWithConfig(IClientConfig config) {
    return new DefaultLoadBalancerRetryHandler(config);
}
 
Example #23
Source File: RibbonTransport.java    From ribbon with Apache License 2.0 4 votes vote down vote up
public static <I, O> RxClient<I, O> newTcpClient(ILoadBalancer loadBalancer, PipelineConfigurator<O, I> pipelineConfigurator, 
        IClientConfig config, RetryHandler retryHandler) {
    return new LoadBalancingTcpClient<I, O>(loadBalancer, config, retryHandler, pipelineConfigurator, poolCleanerScheduler);
}
 
Example #24
Source File: LoadBalancingTcpClient.java    From ribbon with Apache License 2.0 4 votes vote down vote up
public LoadBalancingTcpClient(ILoadBalancer lb, IClientConfig config,
        RetryHandler retryHandler,
        PipelineConfigurator<O, I> pipelineConfigurator, ScheduledExecutorService poolCleanerScheduler) {
    super(lb, config, retryHandler, pipelineConfigurator, poolCleanerScheduler);
}
 
Example #25
Source File: NettyClientTest.java    From ribbon with Apache License 2.0 4 votes vote down vote up
@Test
public void testLoadBalancingWithTwoServers() throws Exception {
    MockWebServer server = new MockWebServer();
    String content = "{\"name\": \"ribbon\", \"age\": 2}";
    server.enqueue(new MockResponse().setResponseCode(200).setHeader("Content-type", "application/json")
            .setBody(content));       
    server.play();

    IClientConfig config = DefaultClientConfigImpl.getClientConfigWithDefaultValues();
            
    HttpClientRequest<ByteBuf> request = HttpClientRequest.createPost("/testAsync/person")
            .withContent(SerializationUtils.serializeToBytes(JacksonCodec.getInstance(), EmbeddedResources.defaultPerson, null))
            .withHeader("Content-type", "application/json");
    NettyHttpLoadBalancerErrorHandler errorHandler = new NettyHttpLoadBalancerErrorHandler(1, 3, true);
    BaseLoadBalancer lb = new BaseLoadBalancer(new DummyPing(), new AvailabilityFilteringRule());
    LoadBalancingHttpClient<ByteBuf, ByteBuf> lbObservables = RibbonTransport.newHttpClient(lb, config, errorHandler);
    HttpClientListener externalListener = HttpClientListener.newHttpListener("external");
    lbObservables.subscribe(externalListener);
    Server server1 = new Server("localhost:" + server.getPort());
    Server server2 = new Server("localhost:" + port);
    
    lb.setServersList(Lists.newArrayList(server1, server2));
    RetryHandler handler = new RequestSpecificRetryHandler(true, true, errorHandler, null) {
        @Override
        public boolean isRetriableException(Throwable e, boolean sameServer) {
            return true;
        }
    };
    Observable<Person> observableWithRetries = getPersonObservable(lbObservables.submit(request, handler, null));
    ObserverWithLatch<Person> observer = new ObserverWithLatch<Person>();
    observableWithRetries.subscribe(observer);
    observer.await();
    if (observer.error != null) {
        observer.error.printStackTrace();
    }
    assertEquals("ribbon", observer.obj.name);
    assertEquals(EmbeddedResources.defaultPerson.age, observer.obj.age);
    
    observer = new ObserverWithLatch<Person>();
    observableWithRetries = getPersonObservable(lbObservables.submit(request, handler, null));
    observableWithRetries.subscribe(observer);
    observer.await();
    if (observer.error != null) {
        observer.error.printStackTrace();
    }
    assertEquals("ribbon", observer.obj.name);
    assertEquals(2, observer.obj.age);
    
    ServerStats stats = lbObservables.getServerStats(server1);
    server.shutdown();
    // assertEquals(1, stats.getTotalRequestsCount());
    assertEquals(0, stats.getActiveRequestsCount());
    
    stats = lbObservables.getServerStats(server2);
    // two requests to bad server because retry same server is set to 1
    assertEquals(1, stats.getTotalRequestsCount());
    assertEquals(0, stats.getActiveRequestsCount());
    assertEquals(0, stats.getSuccessiveConnectionFailureCount());
    final HttpClientListener listener = lbObservables.getListener();
    assertEquals(2, listener.getPoolAcquires());
    waitUntilTrueOrTimeout(1000, new Func0<Boolean>() {
        @Override
        public Boolean call() {
            return listener.getPoolReleases() == 2;
        }
    });
    assertEquals(2, listener.getConnectionCount());
    assertEquals(0, listener.getPoolReuse());
    assertEquals(2, externalListener.getPoolAcquires());
}
 
Example #26
Source File: NettyClientTest.java    From ribbon with Apache License 2.0 4 votes vote down vote up
@Test
public void testLoadBalancingPostWithReadTimeout() throws Exception {
    MockWebServer server = new MockWebServer();
    String content = "{\"name\": \"ribbon\", \"age\": 2}";
    server.enqueue(new MockResponse()
            .setResponseCode(200)
            .setHeader("Content-type", "application/json")
            .setBody(content));       
    server.play();

    IClientConfig config = DefaultClientConfigImpl
            .getClientConfigWithDefaultValues()
            .set(CommonClientConfigKey.ReadTimeout, 100);
    
    HttpClientRequest<ByteBuf> request = HttpClientRequest.createPost("/testAsync/postTimeout")
            .withContent(SerializationUtils.serializeToBytes(JacksonCodec.getInstance(), EmbeddedResources.defaultPerson, null))
            .withHeader("Content-type", "application/json");
    
    NettyHttpLoadBalancerErrorHandler errorHandler = new NettyHttpLoadBalancerErrorHandler(1, 3, true);
    BaseLoadBalancer lb = new BaseLoadBalancer(new DummyPing(), new AvailabilityFilteringRule());
    LoadBalancingHttpClient<ByteBuf, ByteBuf> lbObservables = RibbonTransport.newHttpClient(lb, config, errorHandler);
    Server goodServer = new Server("localhost:" + server.getPort());
    Server badServer = new Server("localhost:" + port);
    List<Server> servers = Lists.newArrayList(badServer, badServer, badServer, goodServer);
    lb.setServersList(servers);
    RetryHandler handler = new RequestSpecificRetryHandler(true, true, errorHandler, null) {
        @Override
        public boolean isRetriableException(Throwable e, boolean sameServer) {
            return true;
        }
    };
    Observable<Person> observableWithRetries = getPersonObservable(lbObservables.submit(request, handler, null));
    ObserverWithLatch<Person> observer = new ObserverWithLatch<Person>();
    observableWithRetries.subscribe(observer);
    observer.await();
    if (observer.error != null) {
        observer.error.printStackTrace();
    }
    assertEquals("ribbon", observer.obj.name);
    assertEquals(2, observer.obj.age);
    ServerStats stats = lbObservables.getServerStats(badServer);
    server.shutdown();
    assertEquals(4, stats.getTotalRequestsCount());
    assertEquals(0, stats.getActiveRequestsCount());
    assertEquals(4, stats.getSuccessiveConnectionFailureCount());
    
    stats = lbObservables.getServerStats(goodServer);
    // two requests to bad server because retry same server is set to 1
    assertEquals(1, stats.getTotalRequestsCount());
    assertEquals(0, stats.getActiveRequestsCount());
    assertEquals(0, stats.getSuccessiveConnectionFailureCount());
}
 
Example #27
Source File: NettyClientTest.java    From ribbon with Apache License 2.0 4 votes vote down vote up
@Test
public void testLoadBalancingPostWithNoRetrySameServer() throws Exception {
    MockWebServer server = new MockWebServer();
    String content = "{\"name\": \"ribbon\", \"age\": 2}";
    server.enqueue(new MockResponse().setResponseCode(200).setHeader("Content-type", "application/json")
            .setBody(content));       
    server.play();

    IClientConfig config = DefaultClientConfigImpl.getClientConfigWithDefaultValues()
            .set(CommonClientConfigKey.ReadTimeout, 100);
    HttpClientRequest<ByteBuf> request = HttpClientRequest.createPost("/testAsync/postTimeout")
            .withContent(SerializationUtils.serializeToBytes(JacksonCodec.getInstance(), EmbeddedResources.defaultPerson, null))
            .withHeader("Content-type", "application/json");
    NettyHttpLoadBalancerErrorHandler errorHandler = new NettyHttpLoadBalancerErrorHandler(0, 3, true);
    BaseLoadBalancer lb = new BaseLoadBalancer(new DummyPing(), new AvailabilityFilteringRule());
    LoadBalancingHttpClient<ByteBuf, ByteBuf> lbObservables = RibbonTransport.newHttpClient(lb, config, errorHandler);
    Server goodServer = new Server("localhost:" + server.getPort());
    Server badServer = new Server("localhost:" + port);
    List<Server> servers = Lists.newArrayList(badServer, badServer, badServer, goodServer);
    lb.setServersList(servers);
    RetryHandler handler = new RequestSpecificRetryHandler(true, true, errorHandler, null) {
        @Override
        public boolean isRetriableException(Throwable e, boolean sameServer) {
            return true;
        }
    };
    Observable<Person> observableWithRetries = getPersonObservable(lbObservables.submit(request, handler, null));
    ObserverWithLatch<Person> observer = new ObserverWithLatch<Person>();
    observableWithRetries.subscribe(observer);
    observer.await();
    if (observer.error != null) {
        observer.error.printStackTrace();
    }
    server.shutdown();
    assertEquals("ribbon", observer.obj.name);
    assertEquals(2, observer.obj.age);
    ServerStats stats = lbObservables.getServerStats(badServer);
    assertEquals(2, stats.getTotalRequestsCount());
    assertEquals(0, stats.getActiveRequestsCount());
    assertEquals(2, stats.getSuccessiveConnectionFailureCount());
    
    stats = lbObservables.getServerStats(goodServer);
    assertEquals(1, stats.getTotalRequestsCount());
    assertEquals(0, stats.getActiveRequestsCount());
    assertEquals(0, stats.getSuccessiveConnectionFailureCount());
}
 
Example #28
Source File: LoadBalancingHttpClient.java    From ribbon with Apache License 2.0 4 votes vote down vote up
public Builder<I, O> withRetryHandler(RetryHandler retryHandler) {
    this.retryHandler = retryHandler;
    return this;
}
 
Example #29
Source File: LoadBalancingTcpClient.java    From ribbon with Apache License 2.0 4 votes vote down vote up
public LoadBalancingTcpClient(IClientConfig config,
        RetryHandler retryHandler,
        PipelineConfigurator<O, I> pipelineConfigurator,
        ScheduledExecutorService poolCleanerScheduler) {
    super(config, retryHandler, pipelineConfigurator, poolCleanerScheduler);
}
 
Example #30
Source File: LoadBalancingUdpClient.java    From ribbon with Apache License 2.0 4 votes vote down vote up
public LoadBalancingUdpClient(ILoadBalancer lb, IClientConfig config,
        RetryHandler retryHandler,
        PipelineConfigurator<O, I> pipelineConfigurator) {
    super(lb, config, retryHandler, pipelineConfigurator);
}