com.netflix.loadbalancer.BaseLoadBalancer Java Examples
The following examples show how to use
com.netflix.loadbalancer.BaseLoadBalancer.
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: NettyClientTest.java From ribbon with Apache License 2.0 | 6 votes |
@Test public void testStreamWithLoadBalancer() throws Exception { // NettyHttpLoadBalancerErrorHandler errorHandler = new NettyHttpLoadBalancerErrorHandler(1, 3, true); // IClientConfig config = DefaultClientConfigImpl.getClientConfigWithDefaultValues().withProperty(CommonClientConfigKey.ConnectTimeout, "1000"); IClientConfig config = IClientConfig.Builder.newBuilder().withRetryOnAllOperations(true) .withMaxAutoRetries(1) .withMaxAutoRetriesNextServer(3) .build(); BaseLoadBalancer lb = new BaseLoadBalancer(new DummyPing(), new AvailabilityFilteringRule()); LoadBalancingHttpClient<ByteBuf, ServerSentEvent> lbObservables = (LoadBalancingHttpClient<ByteBuf, ServerSentEvent>) RibbonTransport.newSSEClient(lb, config); HttpClientRequest<ByteBuf> request = HttpClientRequest.createGet("/testAsync/personStream"); List<Person> result = Lists.newArrayList(); Server goodServer = new Server("localhost:" + port); Server badServer = new Server("localhost:12245"); List<Server> servers = Lists.newArrayList(badServer, badServer, badServer, goodServer); lb.setServersList(servers); result = getPersonListFromResponse(lbObservables.submit(request, null, null)); assertEquals(EmbeddedResources.entityStream, result); }
Example #2
Source File: RetryTest.java From ribbon with Apache License 2.0 | 6 votes |
@Before public void beforeTest() { ConfigurationManager.getConfigInstance().setProperty("RetryTest.ribbon.NFLoadBalancerClassName", BaseLoadBalancer.class.getName()); ConfigurationManager.getConfigInstance().setProperty("RetryTest.ribbon.client.NFLoadBalancerPingClassName", DummyPing.class.getName()); ConfigurationManager.getConfigInstance().setProperty("RetryTest.ribbon.ReadTimeout", "1000"); ConfigurationManager.getConfigInstance().setProperty("RetryTest.ribbon." + CommonClientConfigKey.ConnectTimeout, "500"); ConfigurationManager.getConfigInstance().setProperty("RetryTest.ribbon." + CommonClientConfigKey.OkToRetryOnAllOperations, "true"); client = (RestClient) ClientFactory.getNamedClient("RetryTest"); lb = (BaseLoadBalancer) client.getLoadBalancer(); lb.setServersList(Lists.newArrayList(localServer)); httpClient = NFHttpClientFactory.getNamedNFHttpClient("RetryTest"); connectionPoolManager = (MonitoredConnectionManager) httpClient.getConnectionManager(); client.setMaxAutoRetries(0); client.setMaxAutoRetriesNextServer(0); client.setOkToRetryOnAllOperations(false); lb.setServersList(Lists.newArrayList(localServer)); // reset the server index lb.setRule(new AvailabilityFilteringRule()); lb.getLoadBalancerStats().getSingleServerStat(localServer).clearSuccessiveConnectionFailureCount(); }
Example #3
Source File: RestClientTest.java From ribbon with Apache License 2.0 | 6 votes |
@Test public void testSecureClient2() throws Exception { ConfigurationManager.getConfigInstance().setProperty("test3.ribbon." + CommonClientConfigKey.IsSecure, "true"); ConfigurationManager.getConfigInstance().setProperty("test3.ribbon." + CommonClientConfigKey.TrustStore, secureServer.getTrustStore().getAbsolutePath()); ConfigurationManager.getConfigInstance().setProperty("test3.ribbon." + CommonClientConfigKey.TrustStorePassword, SecureGetTest.PASSWORD); RestClient client = (RestClient) ClientFactory.getNamedClient("test3"); BaseLoadBalancer lb = new BaseLoadBalancer(); Server[] servers = new Server[]{new Server("localhost", secureServer.getServerPort())}; lb.addServers(Arrays.asList(servers)); client.setLoadBalancer(lb); HttpRequest request = HttpRequest.newBuilder().uri(new URI("/")).build(); HttpResponse response = client.executeWithLoadBalancer(request); assertStatusIsOk(response.getStatus()); assertEquals(secureServer.getServerPath("/"), response.getRequestedURI().toString()); }
Example #4
Source File: LoadBalancingRxClient.java From ribbon with Apache License 2.0 | 6 votes |
/** * Add a listener that is responsible for removing an HttpClient and shutting down * its connection pool if it is no longer available from load balancer. */ private void addLoadBalancerListener() { if (!(lbContext.getLoadBalancer() instanceof BaseLoadBalancer)) { return; } ((BaseLoadBalancer) lbContext.getLoadBalancer()).addServerListChangeListener(new ServerListChangeListener() { @Override public void serverListChanged(List<Server> oldList, List<Server> newList) { Set<Server> removedServers = new HashSet<Server>(oldList); removedServers.removeAll(newList); for (Server server: rxClientCache.keySet()) { if (removedServers.contains(server)) { // this server is no longer in UP status removeClient(server); } } } }); }
Example #5
Source File: RestClient.java From s2g-zuul with MIT License | 5 votes |
public void shutdown() { ILoadBalancer lb = this.getLoadBalancer(); if (lb instanceof BaseLoadBalancer) { ((BaseLoadBalancer) lb).shutdown(); } NFHttpClientFactory.shutdownNFHttpClient(restClientName); }
Example #6
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 #7
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 #8
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 #9
Source File: NettyClientTest.java From ribbon with Apache License 2.0 | 5 votes |
@Test public void testObservableWithMultipleServersFailed() throws Exception { IClientConfig config = IClientConfig.Builder.newBuilder() .withDefaultValues() .withRetryOnAllOperations(true) .withMaxAutoRetries(1) .withMaxAutoRetriesNextServer(3) .withConnectTimeout(100) .build(); HttpClientRequest<ByteBuf> request = HttpClientRequest.createGet("/testAsync/person"); BaseLoadBalancer lb = new BaseLoadBalancer(new DummyPing(), new AvailabilityFilteringRule()); LoadBalancingHttpClient<ByteBuf, ByteBuf> lbObservables = RibbonTransport.newHttpClient(lb, config); Server badServer = new Server("localhost:12345"); Server badServer1 = new Server("localhost:12346"); Server badServer2 = new Server("localhost:12347"); List<Server> servers = Lists.newArrayList(badServer, badServer1, badServer2); lb.setServersList(servers); Observable<Person> observableWithRetries = getPersonObservable(lbObservables.submit(request)); ObserverWithLatch<Person> observer = new ObserverWithLatch<Person>(); observableWithRetries.subscribe(observer); observer.await(); assertNull(observer.obj); observer.error.printStackTrace(); 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()); assertEquals(2, stats.getSuccessiveConnectionFailureCount()); }
Example #10
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 #11
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 #12
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 #13
Source File: ServerListRefreshTest.java From ribbon with Apache License 2.0 | 5 votes |
/** * This test ensures that when server list is refreshed in the load balancer, the set of servers * which equals to (oldList - newList) should be removed from the map of cached RxClient. Any server * that is not part of oldList should stay in the map. * * @throws IOException */ @Test public void testServerListRefresh() throws IOException { String content = "Hello world"; MockWebServer server1 = new MockWebServer(); MockWebServer server2 = new MockWebServer(); MockWebServer server3 = new MockWebServer(); MockResponse mockResponse = new MockResponse().setResponseCode(200).setHeader("Content-type", "text/plain") .setBody(content); server1.enqueue(mockResponse); server2.enqueue(mockResponse); server3.enqueue(mockResponse); server1.play(); server2.play(); server3.play(); try { BaseLoadBalancer lb = new BaseLoadBalancer(); List<Server> initialList = Lists.newArrayList(new Server("localhost", server1.getPort()), new Server("localhost", server2.getPort())); lb.setServersList(initialList); LoadBalancingHttpClient<ByteBuf, ByteBuf> client = RibbonTransport.newHttpClient(lb); HttpClientRequest<ByteBuf> request = HttpClientRequest.createGet("/"); client.submit(request).toBlocking().last(); client.submit(request).toBlocking().last(); HttpClientRequest<ByteBuf> request2 = HttpClientRequest.createGet("http://localhost:" + server3.getPort()); client.submit(request2).toBlocking().last(); Set<Server> cachedServers = client.getRxClients().keySet(); assertEquals(Sets.newHashSet(new Server("localhost", server1.getPort()), new Server("localhost", server2.getPort()), new Server("localhost", server3.getPort())), cachedServers); List<Server> newList = Lists.newArrayList(new Server("localhost", server1.getPort()), new Server("localhost", 99999)); lb.setServersList(newList); cachedServers = client.getRxClients().keySet(); assertEquals(Sets.newHashSet(new Server("localhost", server1.getPort()), new Server("localhost", server3.getPort())), cachedServers); } finally { server1.shutdown(); server2.shutdown(); server3.shutdown(); } }
Example #14
Source File: UdpClientTest.java From ribbon with Apache License 2.0 | 5 votes |
@Test public void testUdpClientTimeout() throws Exception { int port = choosePort(); UdpServer<DatagramPacket, DatagramPacket> server = new HelloUdpServer(port, 5000).createServer(); server.start(); BaseLoadBalancer lb = new BaseLoadBalancer(); Server myServer = new Server("localhost", port); lb.setServersList(Lists.newArrayList(myServer)); MyUDPClient client = new MyUDPClient(lb, DefaultClientConfigImpl.getClientConfigWithDefaultValues()); try { String response = client.submit("Is there anybody out there?") .map(new Func1<DatagramPacket, String>() { @Override public String call(DatagramPacket datagramPacket) { return datagramPacket.content().toString(Charset.defaultCharset()); } }) .toBlocking() .first(); fail("Exception expected"); } catch (Exception e) { assertTrue(e.getCause() instanceof TimeoutException); assertEquals(1, client.getLoadBalancerContext().getServerStats(myServer).getSuccessiveConnectionFailureCount()); } finally { server.shutdown(); } }
Example #15
Source File: RestClient.java From ribbon with Apache License 2.0 | 5 votes |
public void shutdown() { ILoadBalancer lb = this.getLoadBalancer(); if (lb instanceof BaseLoadBalancer) { ((BaseLoadBalancer) lb).shutdown(); } NFHttpClientFactory.shutdownNFHttpClient(restClientName); }
Example #16
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 #17
Source File: UdpClientTest.java From ribbon with Apache License 2.0 | 5 votes |
@Test public void testUdpClientWithoutTimeout() throws Exception { int port = choosePort(); UdpServer<DatagramPacket, DatagramPacket> server = new HelloUdpServer(port, 0).createServer(); server.start(); BaseLoadBalancer lb = new BaseLoadBalancer(); lb.setServersList(Lists.newArrayList(new Server("localhost", port))); RxClient<DatagramPacket, DatagramPacket> client = RibbonTransport.newUdpClient(lb, DefaultClientConfigImpl.getClientConfigWithDefaultValues()); try { String response = client.connect().flatMap(new Func1<ObservableConnection<DatagramPacket, DatagramPacket>, Observable<DatagramPacket>>() { @Override public Observable<DatagramPacket> call(ObservableConnection<DatagramPacket, DatagramPacket> connection) { connection.writeStringAndFlush("Is there anybody out there?"); return connection.getInput(); } }).take(1) .map(new Func1<DatagramPacket, String>() { @Override public String call(DatagramPacket datagramPacket) { return datagramPacket.content().toString(Charset.defaultCharset()); } }) .toBlocking() .first(); assertEquals(HelloUdpServer.WELCOME_MSG, response); } finally { server.shutdown(); } }
Example #18
Source File: LoadBalancingReactiveHttpClientTest.java From feign-reactive with Apache License 2.0 | 5 votes |
@BeforeClass public static void setupServersList() throws ClientException { DefaultClientConfigImpl clientConfig = new DefaultClientConfigImpl(); clientConfig.loadDefaultValues(); clientConfig.setProperty(CommonClientConfigKey.NFLoadBalancerClassName, BaseLoadBalancer.class.getName()); ILoadBalancer lb = ClientFactory.registerNamedLoadBalancerFromclientConfig(serviceName, clientConfig); lb.addServers(asList(new Server("localhost", server1.port()), new Server("localhost", server2.port()))); }
Example #19
Source File: HelloClientApplication.java From spring-cloud-release-tools with Apache License 2.0 | 5 votes |
@Bean public ILoadBalancer ribbonLoadBalancer() { // because of this, it doesn't use eureka to lookup the server, // but the classpath is tested BaseLoadBalancer balancer = new BaseLoadBalancer(); balancer.setServersList(Arrays.asList(new Server("example.com", 80))); return balancer; }
Example #20
Source File: TestElasticSearchSink.java From suro with Apache License 2.0 | 4 votes |
@Test public void testCreate() throws IOException { String desc = " {\n" + " \"type\": \"elasticsearch\",\n" + " \"queue4Sink\":{\"type\": \"memory\", \"capacity\": 0 },\n" + " \"batchSize\": 100,\n" + " \"batchTimeout\": 1000,\n" + " \"clientName\": \"es_test\",\n" + " \"cluster.name\": \"es_test\",\n" + " \"addressList\": [\"http://host1:8080\", \"http://host2:8080\"],\n" + " \"indexInfo\":{\n" + " \"type\": \"default\",\n" + " \"indexTypeMap\":{\"routingkey1\":\"index1:type1\", \"routingkey2\":\"index2:type2\"},\n" + " \"idFields\":{\"index\":[\"f1\", \"f2\"]},\n" + " \"timestamp\": {\"field\":\"ts\"},\n" + " \"indexSuffixFormatter\":{\"type\": \"date\", \"properties\":{\"dateFormat\":\"YYYYMMdd\"}}\n" + " }\n" + " }"; final ObjectMapper jsonMapper = new DefaultObjectMapper(); jsonMapper.registerSubtypes(new NamedType(ElasticSearchSink.class, "elasticsearch")); jsonMapper.setInjectableValues(new InjectableValues() { @Override public Object findInjectableValue( Object valueId, DeserializationContext ctxt, BeanProperty forProperty, Object beanInstance ) { if (valueId.equals(ObjectMapper.class.getCanonicalName())) { return jsonMapper; } else { return null; } } }); Sink sink = jsonMapper.readValue(desc, new TypeReference<Sink>(){}); assertTrue(sink instanceof ElasticSearchSink); ElasticSearchSink esSink = (ElasticSearchSink) sink; esSink.createClient(); RestClient client = esSink.getClient(); IClientConfig config = ((BaseLoadBalancer) client.getLoadBalancer()).getClientConfig(); assertTrue(config.get(CommonClientConfigKey.OkToRetryOnAllOperations)); assertEquals(2, config.get(CommonClientConfigKey.MaxAutoRetriesNextServer).intValue()); assertEquals(0, esSink.getSleepOverClientException()); assertFalse(esSink.getReenqueueOnException()); }
Example #21
Source File: URLConnectionLoadBalancer.java From ribbon with Apache License 2.0 | 4 votes |
public LoadBalancerStats getLoadBalancerStats() { return ((BaseLoadBalancer) loadBalancer).getLoadBalancerStats(); }
Example #22
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 #23
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 #24
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 #25
Source File: Demo.java From request-correlation-spring-cloud-starter with Apache License 2.0 | 4 votes |
@Bean public ILoadBalancer ribbonLoadBalancer() { BaseLoadBalancer balancer = new BaseLoadBalancer(); balancer.setServersList(Collections.singletonList(new Server("localhost", this.port))); return balancer; }
Example #26
Source File: OkHttpClientTest.java From feign-okhttp-spring-cloud-starter with Apache License 2.0 | 4 votes |
@Bean public ILoadBalancer ribbonLoadBalancer() { BaseLoadBalancer balancer = new BaseLoadBalancer(); balancer.setServersList(Collections.singletonList(new Server("localhost", this.port))); return balancer; }
Example #27
Source File: OAuth2HttpClientTest.java From feign-oauth2-spring-cloud-starter with Apache License 2.0 | 4 votes |
@Bean public ILoadBalancer ribbonLoadBalancer() { BaseLoadBalancer balancer = new BaseLoadBalancer(); balancer.setServersList(Collections.singletonList(new Server("localhost", this.port))); return balancer; }
Example #28
Source File: NettyClientTest.java From ribbon with Apache License 2.0 | 4 votes |
@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 #29
Source File: NettyClientTest.java From ribbon with Apache License 2.0 | 4 votes |
@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 #30
Source File: NettyClientTest.java From ribbon with Apache License 2.0 | 4 votes |
@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()); }