com.netflix.loadbalancer.LoadBalancerBuilder Java Examples
The following examples show how to use
com.netflix.loadbalancer.LoadBalancerBuilder.
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: ServiceLoadBalancer.java From TeaStore with Apache License 2.0 | 6 votes |
private void updateLoadBalancer(List<Server> newServers) { if (serviceServers == null) { serviceServers = new HashSet<Server>(); } if (newServers == null) { newServers = new ArrayList<Server>(); } //return if nothing changed if ((serviceServers.isEmpty() && newServers.isEmpty()) || (newServers.size() == serviceServers.size() && serviceServers.containsAll(newServers))) { return; } serviceServers = new HashSet<Server>(newServers); loadBalancerModificationLock.writeLock().lock(); try { if (loadBalancer != null) { loadBalancer.shutdown(); } loadBalancer = LoadBalancerBuilder.newBuilder().buildFixedServerListLoadBalancer(newServers); for (EndpointClientCollection<?> lb : endpointMap.values()) { lb.updateServers(newServers); } } finally { loadBalancerModificationLock.writeLock().unlock(); } }
Example #2
Source File: LBBuilderTest.java From ribbon with Apache License 2.0 | 6 votes |
@Test public void testBuildWithDiscoveryEnabledNIWSServerList() { IRule rule = new AvailabilityFilteringRule(); ServerList<DiscoveryEnabledServer> list = new DiscoveryEnabledNIWSServerList("dummy:7001"); ServerListFilter<DiscoveryEnabledServer> filter = new ZoneAffinityServerListFilter<>(); ZoneAwareLoadBalancer<DiscoveryEnabledServer> lb = LoadBalancerBuilder.<DiscoveryEnabledServer>newBuilder() .withDynamicServerList(list) .withRule(rule) .withServerListFilter(filter) .buildDynamicServerListLoadBalancer(); assertNotNull(lb); assertEquals(Lists.newArrayList(expected), lb.getAllServers()); assertSame(filter, lb.getFilter()); assertSame(list, lb.getServerListImpl()); Server server = lb.chooseServer(); // make sure load balancer does not recreate the server instance assertTrue(server instanceof DiscoveryEnabledServer); }
Example #3
Source File: LBBuilderTest.java From ribbon with Apache License 2.0 | 6 votes |
@Test public void testBuildWithDiscoveryEnabledNIWSServerListAndUpdater() { IRule rule = new AvailabilityFilteringRule(); ServerList<DiscoveryEnabledServer> list = new DiscoveryEnabledNIWSServerList("dummy:7001"); ServerListFilter<DiscoveryEnabledServer> filter = new ZoneAffinityServerListFilter<>(); ServerListUpdater updater = new PollingServerListUpdater(); ZoneAwareLoadBalancer<DiscoveryEnabledServer> lb = LoadBalancerBuilder.<DiscoveryEnabledServer>newBuilder() .withDynamicServerList(list) .withRule(rule) .withServerListFilter(filter) .withServerListUpdater(updater) .buildDynamicServerListLoadBalancerWithUpdater(); assertNotNull(lb); assertEquals(Lists.newArrayList(expected), lb.getAllServers()); assertSame(filter, lb.getFilter()); assertSame(list, lb.getServerListImpl()); assertSame(updater, lb.getServerListUpdater()); Server server = lb.chooseServer(); // make sure load balancer does not recreate the server instance assertTrue(server instanceof DiscoveryEnabledServer); }
Example #4
Source File: LBBuilderTest.java From ribbon with Apache License 2.0 | 6 votes |
@Test public void testBuildWithArchaiusProperties() { Configuration config = ConfigurationManager.getConfigInstance(); config.setProperty("client1.niws.client." + Keys.DeploymentContextBasedVipAddresses, "dummy:7001"); config.setProperty("client1.niws.client." + Keys.InitializeNFLoadBalancer, "true"); config.setProperty("client1.niws.client." + Keys.NFLoadBalancerClassName, DynamicServerListLoadBalancer.class.getName()); config.setProperty("client1.niws.client." + Keys.NFLoadBalancerRuleClassName, RoundRobinRule.class.getName()); config.setProperty("client1.niws.client." + Keys.NIWSServerListClassName, DiscoveryEnabledNIWSServerList.class.getName()); config.setProperty("client1.niws.client." + Keys.NIWSServerListFilterClassName, ZoneAffinityServerListFilter.class.getName()); config.setProperty("client1.niws.client." + Keys.ServerListUpdaterClassName, PollingServerListUpdater.class.getName()); IClientConfig clientConfig = IClientConfig.Builder.newBuilder(NiwsClientConfig.class, "client1").build(); ILoadBalancer lb = LoadBalancerBuilder.newBuilder().withClientConfig(clientConfig).buildLoadBalancerFromConfigWithReflection(); assertNotNull(lb); assertEquals(DynamicServerListLoadBalancer.class.getName(), lb.getClass().getName()); DynamicServerListLoadBalancer<Server> dynamicLB = (DynamicServerListLoadBalancer<Server>) lb; assertTrue(dynamicLB.getServerListUpdater() instanceof PollingServerListUpdater); assertTrue(dynamicLB.getFilter() instanceof ZoneAffinityServerListFilter); assertTrue(dynamicLB.getRule() instanceof RoundRobinRule); assertTrue(dynamicLB.getPing() instanceof DummyPing); assertEquals(Lists.newArrayList(expected), lb.getAllServers()); }
Example #5
Source File: ListenerTest.java From ribbon with Apache License 2.0 | 5 votes |
@Test public void testSuccessExecutionOnAbosoluteURI() throws IOException { MockWebServer server = new MockWebServer(); String content = "OK"; server.enqueue(new MockResponse().setResponseCode(200).setHeader("Content-type", "application/json") .setBody(content)); server.play(); IClientConfig config = DefaultClientConfigImpl.getClientConfigWithDefaultValues().withProperty(CommonClientConfigKey.ConnectTimeout, "2000") .withProperty(CommonClientConfigKey.MaxAutoRetries, 1) .withProperty(CommonClientConfigKey.MaxAutoRetriesNextServer, 1); HttpClientRequest<ByteBuf> request = HttpClientRequest.createGet("http://localhost:" + server.getPort() + "/testAsync/person"); Server badServer = new Server("localhost:12345"); Server goodServer = new Server("localhost:" + server.getPort()); List<Server> servers = Lists.newArrayList(goodServer, badServer); BaseLoadBalancer lb = LoadBalancerBuilder.<Server>newBuilder() .withRule(new AvailabilityFilteringRule()) .withPing(new DummyPing()) .buildFixedServerListLoadBalancer(servers); IClientConfig overrideConfig = DefaultClientConfigImpl.getEmptyConfig().set(CommonClientConfigKey.ConnectTimeout, 500); TestExecutionListener<ByteBuf, ByteBuf> listener = new TestExecutionListener<ByteBuf, ByteBuf>(request, overrideConfig); List<ExecutionListener<HttpClientRequest<ByteBuf>, HttpClientResponse<ByteBuf>>> listeners = Lists.<ExecutionListener<HttpClientRequest<ByteBuf>, HttpClientResponse<ByteBuf>>>newArrayList(listener); LoadBalancingHttpClient<ByteBuf, ByteBuf> client = RibbonTransport.newHttpClient(lb, config, new NettyHttpLoadBalancerErrorHandler(config), listeners); HttpClientResponse<ByteBuf> response = client.submit(request, null, overrideConfig).toBlocking().last(); assertEquals(200, response.getStatus().code()); assertEquals(1, listener.executionStartCounter.get()); assertEquals(1, listener.startWithServerCounter.get()); assertEquals(0, listener.exceptionWithServerCounter.get()); assertEquals(0, listener.executionFailedCounter.get()); assertEquals(1, listener.executionSuccessCounter.get()); assertEquals(500, listener.getContext().getClientProperty(CommonClientConfigKey.ConnectTimeout).intValue()); assertTrue(listener.isContextChecked()); assertTrue(listener.isCheckExecutionInfo()); assertSame(response, listener.getResponse()); }
Example #6
Source File: ListenerTest.java From ribbon with Apache License 2.0 | 5 votes |
@Test public void testFailedExecutionForAbsoluteURI() { IClientConfig config = DefaultClientConfigImpl .getClientConfigWithDefaultValues() .withProperty(CommonClientConfigKey.ConnectTimeout, "100") .withProperty(CommonClientConfigKey.MaxAutoRetries, 1) .withProperty(CommonClientConfigKey.MaxAutoRetriesNextServer, 1); HttpClientRequest<ByteBuf> request = HttpClientRequest.createGet("http://xyz.unknowhost.xyz/testAsync/person"); Server badServer = new Server("localhost:12345"); Server badServer2 = new Server("localhost:34567"); List<Server> servers = Lists.newArrayList(badServer, badServer2); BaseLoadBalancer lb = LoadBalancerBuilder.<Server>newBuilder() .withRule(new AvailabilityFilteringRule()) .withPing(new DummyPing()) .buildFixedServerListLoadBalancer(servers); IClientConfig overrideConfig = DefaultClientConfigImpl.getEmptyConfig(); TestExecutionListener<ByteBuf, ByteBuf> listener = new TestExecutionListener<ByteBuf, ByteBuf>(request, overrideConfig); List<ExecutionListener<HttpClientRequest<ByteBuf>, HttpClientResponse<ByteBuf>>> listeners = Lists.<ExecutionListener<HttpClientRequest<ByteBuf>, HttpClientResponse<ByteBuf>>>newArrayList(listener); LoadBalancingHttpClient<ByteBuf, ByteBuf> client = RibbonTransport.newHttpClient(lb, config, new NettyHttpLoadBalancerErrorHandler(config), listeners); try { client.submit(request, null, overrideConfig).toBlocking().last(); fail("Exception expected"); } catch(Exception e) { assertNotNull(e); } assertEquals(1, listener.executionStartCounter.get()); assertEquals(2, listener.startWithServerCounter.get()); assertEquals(2, listener.exceptionWithServerCounter.get()); assertEquals(1, listener.executionFailedCounter.get()); assertTrue(listener.isContextChecked()); assertTrue(listener.isCheckExecutionInfo()); assertTrue(listener.getFinalThrowable() instanceof ClientException); }
Example #7
Source File: ListenerTest.java From ribbon with Apache License 2.0 | 5 votes |
@Test public void testFailedExecution() { IClientConfig config = DefaultClientConfigImpl.getClientConfigWithDefaultValues() .withProperty(CommonClientConfigKey.ConnectTimeout, "100") .withProperty(CommonClientConfigKey.MaxAutoRetries, 1) .withProperty(CommonClientConfigKey.MaxAutoRetriesNextServer, 1); System.out.println(config); HttpClientRequest<ByteBuf> request = HttpClientRequest.createGet("/testAsync/person"); Server badServer = new Server("localhost:12345"); Server badServer2 = new Server("localhost:34567"); List<Server> servers = Lists.newArrayList(badServer, badServer2); BaseLoadBalancer lb = LoadBalancerBuilder.<Server>newBuilder() .withRule(new AvailabilityFilteringRule()) .withPing(new DummyPing()) .buildFixedServerListLoadBalancer(servers); IClientConfig overrideConfig = DefaultClientConfigImpl.getEmptyConfig(); TestExecutionListener<ByteBuf, ByteBuf> listener = new TestExecutionListener<ByteBuf, ByteBuf>(request, overrideConfig); List<ExecutionListener<HttpClientRequest<ByteBuf>, HttpClientResponse<ByteBuf>>> listeners = Lists.<ExecutionListener<HttpClientRequest<ByteBuf>, HttpClientResponse<ByteBuf>>>newArrayList(listener); LoadBalancingHttpClient<ByteBuf, ByteBuf> client = RibbonTransport.newHttpClient(lb, config, new NettyHttpLoadBalancerErrorHandler(config), listeners); try { client.submit(request, null, overrideConfig).toBlocking().last(); fail("Exception expected"); } catch(Exception e) { assertNotNull(e); } assertEquals(1, listener.executionStartCounter.get()); assertEquals(4, listener.startWithServerCounter.get()); assertEquals(4, listener.exceptionWithServerCounter.get()); assertEquals(1, listener.executionFailedCounter.get()); assertTrue(listener.isContextChecked()); assertTrue(listener.isCheckExecutionInfo()); assertNotNull(listener.getFinalThrowable()); listener.getFinalThrowable().printStackTrace(); assertTrue(listener.getFinalThrowable() instanceof ClientException); assertEquals(100, listener.getContext().getClientProperty(CommonClientConfigKey.ConnectTimeout).intValue()); }
Example #8
Source File: NettyClientTest.java From ribbon with Apache License 2.0 | 5 votes |
@Test public void testObservableWithRetrySameServer() throws Exception { IClientConfig config = DefaultClientConfigImpl.getClientConfigWithDefaultValues().withProperty(CommonClientConfigKey.ConnectTimeout, "1000"); HttpClientRequest<ByteBuf> request = HttpClientRequest.createGet("/testAsync/person"); Server badServer = new Server("localhost:12345"); Server goodServer = new Server("localhost:" + port); List<Server> servers = Lists.newArrayList(badServer, badServer, goodServer); BaseLoadBalancer lb = LoadBalancerBuilder.<Server>newBuilder() .withRule(new AvailabilityFilteringRule()) .withPing(new DummyPing()) .buildFixedServerListLoadBalancer(servers); LoadBalancingHttpClient<ByteBuf, ByteBuf> lbObservables = RibbonTransport.newHttpClient(lb, config, new NettyHttpLoadBalancerErrorHandler(1, 0, true)); Observable<Person> observableWithRetries = getPersonObservable(lbObservables.submit(request)); ObserverWithLatch<Person> observer = new ObserverWithLatch<Person>(); observableWithRetries.subscribe(observer); observer.await(); assertNull(observer.obj); assertTrue(observer.error instanceof ClientException); ServerStats stats = lbObservables.getServerStats(badServer); // two requests to bad server because retry same server is set to 1 assertEquals(2, stats.getTotalRequestsCount()); assertEquals(0, stats.getActiveRequestsCount()); stats = lbObservables.getServerStats(goodServer); assertEquals(0, stats.getTotalRequestsCount()); }
Example #9
Source File: NettyClientTest.java From ribbon with Apache License 2.0 | 5 votes |
@Test public void testObservableWithMultipleServersWithOverrideRxConfig() throws Exception { IClientConfig config = DefaultClientConfigImpl.getClientConfigWithDefaultValues().withProperty(CommonClientConfigKey.ConnectTimeout, "1000"); HttpClientRequest<ByteBuf> request = HttpClientRequest.createGet("/testAsync/person"); Server badServer = new Server("localhost:12345"); Server goodServer = new Server("localhost:" + port); List<Server> servers = Lists.newArrayList(badServer, badServer, badServer, goodServer); BaseLoadBalancer lb = LoadBalancerBuilder.<Server>newBuilder() .withRule(new AvailabilityFilteringRule()) .withPing(new DummyPing()) .buildFixedServerListLoadBalancer(servers); LoadBalancingHttpClient<ByteBuf, ByteBuf> lbObservables = RibbonTransport.newHttpClient(lb, config, new NettyHttpLoadBalancerErrorHandler(1, 3, true)); HttpClientConfig rxconfig = HttpClientConfig.Builder.newDefaultConfig(); Person person = getPersonObservable(lbObservables.submit(request, rxconfig)).toBlocking().single(); assertEquals(EmbeddedResources.defaultPerson, person); ServerStats stats = lbObservables.getServerStats(badServer); // two requests to bad server because retry same server is set to 1 assertEquals(4, stats.getTotalRequestsCount()); assertEquals(0, stats.getActiveRequestsCount()); assertEquals(4, stats.getSuccessiveConnectionFailureCount()); stats = lbObservables.getServerStats(goodServer); assertEquals(1, stats.getTotalRequestsCount()); assertEquals(0, stats.getActiveRequestsCount()); assertEquals(0, stats.getSuccessiveConnectionFailureCount()); final HttpClientListener listener = lbObservables.getListener(); assertEquals(1, listener.getConnectionCount()); waitUntilTrueOrTimeout(1000, new Func0<Boolean>() { @Override public Boolean call() { return listener.getPoolReleases() == 1; } }); }
Example #10
Source File: NettyClientTest.java From ribbon with Apache License 2.0 | 5 votes |
@Test public void testObservableWithMultipleServers() throws Exception { IClientConfig config = DefaultClientConfigImpl .getClientConfigWithDefaultValues() .withProperty(CommonClientConfigKey.ConnectTimeout, "1000"); HttpClientRequest<ByteBuf> request = HttpClientRequest.createGet("/testAsync/person"); Server badServer = new Server("localhost:12345"); Server goodServer = new Server("localhost:" + port); List<Server> servers = Lists.newArrayList(badServer, badServer, badServer, goodServer); BaseLoadBalancer lb = LoadBalancerBuilder.<Server>newBuilder() .withRule(new AvailabilityFilteringRule()) .withPing(new DummyPing()) .buildFixedServerListLoadBalancer(servers); LoadBalancingHttpClient<ByteBuf, ByteBuf> lbObservables = RibbonTransport.newHttpClient(lb, config, new NettyHttpLoadBalancerErrorHandler(1, 3, true)); Person person = getPersonObservable(lbObservables.submit(request)).toBlocking().single(); assertEquals(EmbeddedResources.defaultPerson, person); ServerStats stats = lbObservables.getServerStats(badServer); // two requests to bad server because retry same server is set to 1 assertEquals(4, stats.getTotalRequestsCount()); assertEquals(0, stats.getActiveRequestsCount()); assertEquals(4, stats.getSuccessiveConnectionFailureCount()); stats = lbObservables.getServerStats(goodServer); assertEquals(1, stats.getTotalRequestsCount()); assertEquals(0, stats.getActiveRequestsCount()); assertEquals(0, stats.getSuccessiveConnectionFailureCount()); person = getPersonObservable(lbObservables.submit(request)).toBlocking().single(); assertEquals(EmbeddedResources.defaultPerson, person); HttpClientListener listener = lbObservables.getListener(); assertEquals(1, listener.getPoolReuse()); }
Example #11
Source File: LoadBalancingRxClientWithPoolOptions.java From ribbon with Apache License 2.0 | 5 votes |
public LoadBalancingRxClientWithPoolOptions(IClientConfig config, RetryHandler retryHandler, PipelineConfigurator<O, I> pipelineConfigurator, ScheduledExecutorService poolCleanerScheduler) { this(LoadBalancerBuilder.newBuilder().withClientConfig(config).buildDynamicServerListLoadBalancer(), config, retryHandler, pipelineConfigurator, poolCleanerScheduler); }
Example #12
Source File: LoadBalancingRxClient.java From ribbon with Apache License 2.0 | 5 votes |
public LoadBalancingRxClient(IClientConfig config, RetryHandler defaultRetryHandler, PipelineConfigurator<O, I> pipelineConfigurator) { this(LoadBalancerBuilder.newBuilder().withClientConfig(config).buildLoadBalancerFromConfigWithReflection(), config, defaultRetryHandler, pipelineConfigurator ); }
Example #13
Source File: LoadBalancingHttpClient.java From ribbon with Apache License 2.0 | 5 votes |
public LoadBalancingHttpClient<I, O> build() { if (retryHandler == null) { retryHandler = new NettyHttpLoadBalancerErrorHandler(); } if (config == null) { config = DefaultClientConfigImpl.getClientConfigWithDefaultValues(); } if (lb == null) { lb = LoadBalancerBuilder.newBuilder().withClientConfig(config).buildLoadBalancerFromConfigWithReflection(); } if (listeners == null) { listeners = Collections.<ExecutionListener<HttpClientRequest<I>, HttpClientResponse<O>>>emptyList(); } if (backoffStrategy == null) { backoffStrategy = new Func1<Integer, Integer>() { @Override public Integer call(Integer backoffCount) { int interval = config.getOrDefault(IClientConfigKey.Keys.BackoffInterval); if (backoffCount < 0) { backoffCount = 0; } else if (backoffCount > 10) { // Reasonable upper bound backoffCount = 10; } return (int)Math.pow(2, backoffCount) * interval; } }; } if (responseToErrorPolicy == null) { responseToErrorPolicy = new DefaultResponseToErrorPolicy<O>(); } return build.call(this); }
Example #14
Source File: LBBuilderTest.java From ribbon with Apache License 2.0 | 5 votes |
@Test public void testBuildStaticServerListLoadBalancer() { List<Server> list = Lists.newArrayList(expected, expected); IRule rule = new AvailabilityFilteringRule(); IClientConfig clientConfig = IClientConfig.Builder.newBuilder() .withDefaultValues() .withMaxAutoRetriesNextServer(3).build(); assertEquals(3, clientConfig.get(Keys.MaxAutoRetriesNextServer).intValue()); BaseLoadBalancer lb = LoadBalancerBuilder.newBuilder() .withRule(rule) .buildFixedServerListLoadBalancer(list); assertEquals(list, lb.getAllServers()); assertSame(rule, lb.getRule()); }
Example #15
Source File: HttpOutputPlugin.java From ffwd with Apache License 2.0 | 5 votes |
@Override public Module module(final Key<PluginSink> key, final String id) { return new OutputPluginModule(id) { @Provides @Singleton @Named("http") public ExecutorService threadPool() { return Executors.newCachedThreadPool( new ThreadFactoryBuilder().setNameFormat("ffwd-okhttp-async-%d").build()); } @Provides @Singleton public ILoadBalancer setupRibbonClient( HttpPing httpPing, @Named("searchDomain") final Optional<String> searchDomain ) { return discovery .apply(LoadBalancerBuilder.newBuilder(), searchDomain) .withPing(httpPing) .buildDynamicServerListLoadBalancer(); } @Override protected void configure() { final Key<HttpPluginSink> sinkKey = Key.get(HttpPluginSink.class, Names.named("httpSink")); bind(sinkKey).to(HttpPluginSink.class).in(Scopes.SINGLETON); install(wrapPluginSink(sinkKey, key)); expose(key); } }; }
Example #16
Source File: ListenerTest.java From ribbon with Apache License 2.0 | 4 votes |
@Test public void testAbortedExecutionOnServer() { IClientConfig config = DefaultClientConfigImpl.getClientConfigWithDefaultValues().withProperty(CommonClientConfigKey.ConnectTimeout, "100") .withProperty(CommonClientConfigKey.MaxAutoRetries, 1) .withProperty(CommonClientConfigKey.MaxAutoRetriesNextServer, 1); HttpClientRequest<ByteBuf> request = HttpClientRequest.createGet("/testAsync/person"); Server badServer = new Server("localhost:12345"); Server badServer2 = new Server("localhost:34567"); List<Server> servers = Lists.newArrayList(badServer, badServer2); BaseLoadBalancer lb = LoadBalancerBuilder.<Server>newBuilder() .withRule(new AvailabilityFilteringRule()) .withPing(new DummyPing()) .buildFixedServerListLoadBalancer(servers); IClientConfig overrideConfig = DefaultClientConfigImpl.getEmptyConfig(); TestExecutionListener listener = new TestExecutionListener(request, overrideConfig) { @Override public void onStartWithServer(ExecutionContext context, ExecutionInfo info) { throw new AbortExecutionException("exit now"); } }; List<ExecutionListener<HttpClientRequest<ByteBuf>, HttpClientResponse<ByteBuf>>> listeners = Lists.<ExecutionListener<HttpClientRequest<ByteBuf>, HttpClientResponse<ByteBuf>>>newArrayList(listener); LoadBalancingHttpClient<ByteBuf, ByteBuf> client = RibbonTransport.newHttpClient(lb, config, new NettyHttpLoadBalancerErrorHandler(config), listeners); final CountDownLatch latch = new CountDownLatch(1); final AtomicReference<Throwable> ref = new AtomicReference<Throwable>(); client.submit(request, null, overrideConfig).subscribe(new Action1<HttpClientResponse<ByteBuf>>() { @Override public void call(HttpClientResponse<ByteBuf> byteBufHttpClientResponse) { } }, new Action1<Throwable>() { @Override public void call(Throwable throwable) { ref.set(throwable); latch.countDown(); } }); try { latch.await(500, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { e.printStackTrace(); } assertTrue(ref.get() instanceof AbortExecutionException); }
Example #17
Source File: URLConnectionLoadBalancer.java From ribbon with Apache License 2.0 | 4 votes |
public URLConnectionLoadBalancer(List<Server> serverList) { loadBalancer = LoadBalancerBuilder.newBuilder().buildFixedServerListLoadBalancer(serverList); }
Example #18
Source File: ListenerTest.java From ribbon with Apache License 2.0 | 4 votes |
@Test public void testAbortedExecution() { IClientConfig config = DefaultClientConfigImpl.getClientConfigWithDefaultValues().withProperty(CommonClientConfigKey.ConnectTimeout, "100") .withProperty(CommonClientConfigKey.MaxAutoRetries, 1) .withProperty(CommonClientConfigKey.MaxAutoRetriesNextServer, 1); HttpClientRequest<ByteBuf> request = HttpClientRequest.createGet("/testAsync/person"); Server badServer = new Server("localhost:12345"); Server badServer2 = new Server("localhost:34567"); List<Server> servers = Lists.newArrayList(badServer, badServer2); BaseLoadBalancer lb = LoadBalancerBuilder.<Server>newBuilder() .withRule(new AvailabilityFilteringRule()) .withPing(new DummyPing()) .buildFixedServerListLoadBalancer(servers); IClientConfig overrideConfig = DefaultClientConfigImpl.getEmptyConfig(); TestExecutionListener listener = new TestExecutionListener(request, overrideConfig) { @Override public void onExecutionStart(ExecutionContext context) { throw new AbortExecutionException("exit now"); } }; List<ExecutionListener<HttpClientRequest<ByteBuf>, HttpClientResponse<ByteBuf>>> listeners = Lists.<ExecutionListener<HttpClientRequest<ByteBuf>, HttpClientResponse<ByteBuf>>>newArrayList(listener); LoadBalancingHttpClient<ByteBuf, ByteBuf> client = RibbonTransport.newHttpClient(lb, config, new NettyHttpLoadBalancerErrorHandler(config), listeners); final CountDownLatch latch = new CountDownLatch(1); final AtomicReference<Throwable> ref = new AtomicReference<Throwable>(); client.submit(request, null, overrideConfig).subscribe(new Action1<HttpClientResponse<ByteBuf>>() { @Override public void call(HttpClientResponse<ByteBuf> byteBufHttpClientResponse) { } }, new Action1<Throwable>() { @Override public void call(Throwable throwable) { ref.set(throwable); latch.countDown(); } }); try { latch.await(500, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { e.printStackTrace(); } assertTrue(ref.get() instanceof AbortExecutionException); }
Example #19
Source File: ListenerTest.java From ribbon with Apache License 2.0 | 4 votes |
@Test public void testSuccessExecution() throws IOException { MockWebServer server = new MockWebServer(); String content = "OK"; server.enqueue(new MockResponse() .setResponseCode(200) .setHeader("Content-type", "application/json") .setBody(content)); server.play(); IClientConfig config = DefaultClientConfigImpl .getClientConfigWithDefaultValues() .withProperty(CommonClientConfigKey.ConnectTimeout, "2000") .withProperty(CommonClientConfigKey.MaxAutoRetries, 1) .withProperty(CommonClientConfigKey.MaxAutoRetriesNextServer, 1); System.out.println(config); HttpClientRequest<ByteBuf> request = HttpClientRequest.createGet("/testAsync/person"); Server badServer = new Server("localhost:12345"); Server goodServer = new Server("localhost:" + server.getPort()); List<Server> servers = Lists.newArrayList(goodServer, badServer); BaseLoadBalancer lb = LoadBalancerBuilder.newBuilder() .withRule(new AvailabilityFilteringRule()) .withPing(new DummyPing()) .buildFixedServerListLoadBalancer(servers); IClientConfig overrideConfig = DefaultClientConfigImpl .getEmptyConfig() .set(CommonClientConfigKey.ConnectTimeout, 500); TestExecutionListener<ByteBuf, ByteBuf> listener = new TestExecutionListener<>(request, overrideConfig); List<ExecutionListener<HttpClientRequest<ByteBuf>, HttpClientResponse<ByteBuf>>> listeners = Lists.newArrayList(listener); LoadBalancingHttpClient<ByteBuf, ByteBuf> client = RibbonTransport.newHttpClient(lb, config, new NettyHttpLoadBalancerErrorHandler(config), listeners); HttpClientResponse<ByteBuf> response = client.submit(request, null, overrideConfig).toBlocking().last(); System.out.println(listener); assertEquals(200, response.getStatus().code()); assertEquals(1, listener.executionStartCounter.get()); assertEquals(3, listener.startWithServerCounter.get()); assertEquals(2, listener.exceptionWithServerCounter.get()); assertEquals(0, listener.executionFailedCounter.get()); assertEquals(1, listener.executionSuccessCounter.get()); assertEquals(500, listener.getContext().getClientProperty(CommonClientConfigKey.ConnectTimeout).intValue()); assertTrue(listener.isContextChecked()); assertTrue(listener.isCheckExecutionInfo()); assertSame(response, listener.getResponse()); }
Example #20
Source File: RibbonJerseyClientBuilder.java From dropwizard-consul with Apache License 2.0 | 4 votes |
/** * Builds a new {@link RibbonJerseyClient} with an existing Jersey Client and service discoverer * * @param name Client name * @param jerseyClient Jersey Client * @param serviceDiscoverer Service discoverer * @return new RibbonJerseyClient */ public RibbonJerseyClient build( final String name, final Client jerseyClient, final ConsulServiceDiscoverer serviceDiscoverer) { // dynamic server list that is refreshed from Consul final ConsulServerList serverList = new ConsulServerList(consul, serviceDiscoverer); // build a new load balancer based on the configuration final DefaultClientConfigImpl clientConfig = new DefaultClientConfigImpl(); clientConfig.set(CommonClientConfigKey.AppName, name); clientConfig.set( CommonClientConfigKey.ServerListRefreshInterval, Ints.checkedCast(configuration.getRefreshInterval().toMilliseconds())); final ZoneAwareLoadBalancer<Server> loadBalancer = LoadBalancerBuilder.newBuilder() .withClientConfig(clientConfig) .withRule(new WeightedResponseTimeRule()) .withDynamicServerList(serverList) .buildDynamicServerListLoadBalancer(); final RibbonJerseyClient client = new RibbonJerseyClient(loadBalancer, jerseyClient); environment .lifecycle() .manage( new Managed() { @Override public void start() throws Exception { // nothing to start } @Override public void stop() throws Exception { client.close(); } }); return client; }