@Test public void testRetryNonBlocking() throws IOException, InterruptedException, ExecutionException { AsyncHttpClientConfig config = config() .setKeepAlive(true) .setMaxConnections(100) .setConnectTimeout(60000) .setRequestTimeout(30000) .build(); try (AsyncHttpClient client = asyncHttpClient(config)) { List<ListenableFuture<Response>> res = new ArrayList<>(); for (int i = 0; i < 32; i++) { res.add(testMethodRequest(client, 3, "servlet", UUID.randomUUID().toString())); } StringBuilder b = new StringBuilder(); for (ListenableFuture<Response> r : res) { Response theres = r.get(); assertEquals(200, theres.getStatusCode()); b.append("==============\r\n") .append("Response Headers\r\n"); HttpHeaders heads = theres.getHeaders(); b.append(heads).append("\r\n") .append("==============\r\n"); } System.out.println(b.toString()); System.out.flush(); } }
@Test public void testRetryNonBlockingAsyncConnect() throws IOException, InterruptedException, ExecutionException { AsyncHttpClientConfig config = config() .setKeepAlive(true) .setMaxConnections(100) .setConnectTimeout(60000) .setRequestTimeout(30000) .build(); try (AsyncHttpClient client = asyncHttpClient(config)) { List<ListenableFuture<Response>> res = new ArrayList<>(); for (int i = 0; i < 32; i++) { res.add(testMethodRequest(client, 3, "servlet", UUID.randomUUID().toString())); } StringBuilder b = new StringBuilder(); for (ListenableFuture<Response> r : res) { Response theres = r.get(); assertEquals(theres.getStatusCode(), 200); b.append("==============\r\n") .append("Response Headers\r\n"); HttpHeaders heads = theres.getHeaders(); b.append(heads).append("\r\n") .append("==============\r\n"); } System.out.println(b.toString()); System.out.flush(); } }
try (AsyncHttpClient client = asyncHttpClient(config().setConnectTimeout(timeout))) { TransferCompletionHandler tl = new TransferCompletionHandler(); tl.addTransferListener(new TransferListener() {
/** * Create an instance from a given {@link BulletConfig}. Requires {@link DRPCConfig#DRPC_HTTP_CONNECT_TIMEOUT}, * {@link DRPCConfig#DRPC_HTTP_CONNECT_RETRY_LIMIT}, {@link DRPCConfig#DRPC_SERVERS}, {@link DRPCConfig#DRPC_HTTP_PORT}, * and {@link DRPCConfig#DRPC_HTTP_PATH} to be set. To be used in PubSub.Context#QUERY_SUBMISSION mode. * * @param config A non-null config that contains the required settings. */ public DRPCQueryResultPubscriber(BulletConfig config) { Objects.requireNonNull(config); Number connectTimeout = config.getRequiredConfigAs(DRPCConfig.DRPC_HTTP_CONNECT_TIMEOUT, Number.class); Number retryLimit = config.getRequiredConfigAs(DRPCConfig.DRPC_HTTP_CONNECT_RETRY_LIMIT, Number.class); List<String> servers = (List<String>) config.getRequiredConfigAs(DRPCConfig.DRPC_SERVERS, List.class); String protocol = config.getRequiredConfigAs(DRPCConfig.DRPC_HTTP_PROTOCOL, String.class); String port = config.getRequiredConfigAs(DRPCConfig.DRPC_HTTP_PORT, String.class); String path = config.getRequiredConfigAs(DRPCConfig.DRPC_HTTP_PATH, String.class); String function = config.getRequiredConfigAs(DRPCConfig.DRPC_FUNCTION, String.class); List<String> endpoints = servers.stream() .map(url -> String.format(URL_TEMPLATE, protocol, url, port, path, function)) .collect(Collectors.toList()); this.urls = new RandomPool<>(endpoints); AsyncHttpClientConfig clientConfig = new DefaultAsyncHttpClientConfig.Builder() .setConnectTimeout(connectTimeout.intValue()) .setMaxRequestRetry(retryLimit.intValue()) .setReadTimeout(NO_TIMEOUT) .setRequestTimeout(NO_TIMEOUT) .build(); // This is thread safe client = new DefaultAsyncHttpClient(clientConfig); responses = new ConcurrentLinkedQueue<>(); }
config.setConnectTimeout(timeout); config.setFollowRedirect(false); config.setConnectionTtl((int) (period * 2)); // 2 times the period so it gives a chance under heavy load to reuse connections
/** * Initialize the client config. * * @param requestTimeout Timeout to use for the client configuration. * * @return the set up client */ private static AsyncHttpClient initializeWebClient(int requestTimeout) { LOG.debug("Druid request timeout: {}ms", requestTimeout); List<String> cipherSuites = SYSTEM_CONFIG.getListProperty(SSL_ENABLED_CIPHER_KEY, null); String[] enabledCipherSuites = cipherSuites == null || cipherSuites.isEmpty() ? null : cipherSuites.toArray(new String[cipherSuites.size()]); // Build the configuration AsyncHttpClientConfig config = new DefaultAsyncHttpClientConfig.Builder() .setReadTimeout(requestTimeout) .setRequestTimeout(requestTimeout) .setConnectTimeout(requestTimeout) .setConnectionTtl(requestTimeout) .setPooledConnectionIdleTimeout(requestTimeout) .setEnabledCipherSuites(enabledCipherSuites) .setFollowRedirect(true) .build(); return new DefaultAsyncHttpClient(config); }
public TradeshiftClientConfiguration build() { asyncHttpClientConfig = getAsyncHttpClientConfig() .orElseGet(() -> new DefaultAsyncHttpClientConfig.Builder() .setConnectTimeout(CONNECT_TIMEOUT_IN_MS) .setRequestTimeout(REQUEST_TIMEOUT_IN_MS) .setUserAgent(defaultUserAgent()) .setMaxConnectionsPerHost(MAX_CONNECTIONS_PER_HOST) .addRequestFilter( new RateLimitedThrottleRequestFilter(MAX_CONNECTIONS_PER_HOST, MAX_REQUEST_PER_SECOND, MAX_WAIT_FOR_CONNECTION)) .build()); asyncHttpClient = getAsyncHttpClient() .orElseGet(() -> new DefaultAsyncHttpClient(asyncHttpClientConfig)); httpAuthenticationStrategy = httpAuthenticationStrategy() .orElseGet(XTradeshiftHeadersHttpAuthentication::new); responseErrorReader = responseErrorReaderStrategy().orElseGet(MultiTypeResponseErrorReader::new); return new DefaultTradeshiftClientConfiguration(this); }
/** * Creates a {@link HttpClient} that can be used by the {@link SphereClient}. * @return new http client with custom settings */ public static HttpClient createCustomHttpClient() { final AsyncHttpClientConfig httpClientConfig = new DefaultAsyncHttpClientConfig.Builder() .setEnabledProtocols(new String[]{"TLSv1.2"})//required //examples for configuration .setMaxConnections(500) .setConnectTimeout(10000) // .setProxyServer(proxy) .build(); final AsyncHttpClient asyncHttpClient = new DefaultAsyncHttpClient(httpClientConfig); return AsyncHttpClientAdapter.of(asyncHttpClient); }
/** * Creates a new {@link ManagementClientAsync}. * User should call {@link ManagementClientAsync#close()} at the end of life of the client. * @param namespaceEndpointURI - URI of the namespace connecting to. * @param clientSettings - client settings. */ public ManagementClientAsync(URI namespaceEndpointURI, ClientSettings clientSettings) { this.namespaceEndpointURI = namespaceEndpointURI; this.clientSettings = clientSettings; DefaultAsyncHttpClientConfig.Builder clientBuilder = Dsl.config() .setConnectTimeout((int)CONNECTION_TIMEOUT.toMillis()) .setRequestTimeout((int)this.clientSettings.getOperationTimeout().toMillis()); this.asyncHttpClient = asyncHttpClient(clientBuilder); }
confBuilder.setConnectTimeout(connectTimeoutInSeconds * 1000); confBuilder.setReadTimeout(readTimeoutInSeconds * 1000); confBuilder.setUserAgent(String.format("Pulsar-Java-v%s", getPulsarClientVersion()));
.setConnectTimeout(1000) .setRequestTimeout(5000) .setKeepAlive(true)
.setConnectTimeout(1000) .setRequestTimeout(5000) .setKeepAlive(false)
.setConnectTimeout(1000) .setRequestTimeout(5000) .setKeepAlive(false)
@Test(groups = "online", invocationCount = 4) public void multipleSslRequestsWithDelayAndKeepAlive() throws Exception { AsyncHttpClientConfig config = config() .setFollowRedirect(true) .setKeepAlive(true) .setConnectTimeout(10000) .setPooledConnectionIdleTimeout(60000) .setRequestTimeout(10000) .setMaxConnectionsPerHost(-1) .setMaxConnections(-1) .build(); try (AsyncHttpClient client = asyncHttpClient(config)) { final BoundRequestBuilder builder = client.prepareGet(GOOGLE_HTTPS_URL); final Response response1 = builder.execute().get(); Thread.sleep(4000); final Response response2 = builder.execute().get(); assertNotNull(response1); assertNotNull(response2); } } }
/** * Tests that after a redirect the final url in the response reflect the redirect */ @Test public void testGetRedirectFinalUrl() throws Exception { AsyncHttpClientConfig config = config() .setKeepAlive(true) .setMaxConnectionsPerHost(1) .setMaxConnections(1) .setConnectTimeout(1000) .setRequestTimeout(1000) .setFollowRedirect(true) .build(); try (AsyncHttpClient c = asyncHttpClient(config)) { ListenableFuture<Response> response = c.executeRequest(get(servletEndpointRedirectUrl)); Response res = response.get(); assertNotNull(res.getResponseBody()); assertEquals(res.getUri().toString(), BASE_URL + "/overthere"); } }
@Test public void multipleMaxConnectionOpenTestWithQuery() throws Exception { try (AsyncHttpClient c = asyncHttpClient(config().setKeepAlive(true).setConnectTimeout(5000).setMaxConnections(1))) { String body = "hello there"; // once Response response = c.preparePost(getTargetUrl() + "?foo=bar").setBody(body).execute().get(TIMEOUT, TimeUnit.SECONDS); assertEquals(response.getResponseBody(), "foo_" + body); // twice Exception exception = null; try { response = c.preparePost(getTargetUrl()).setBody(body).execute().get(TIMEOUT, TimeUnit.SECONDS); } catch (Exception ex) { ex.printStackTrace(); exception = ex; } assertNull(exception); assertNotNull(response); assertEquals(response.getStatusCode(), 200); } }
@Test(expectedExceptions = TooManyConnectionsException.class) public void multipleMaxConnectionOpenTest() throws Throwable { try (AsyncHttpClient c = asyncHttpClient(config().setKeepAlive(true).setConnectTimeout(5000).setMaxConnections(1))) { String body = "hello there"; // once Response response = c.preparePost(getTargetUrl()).setBody(body).execute().get(TIMEOUT, TimeUnit.SECONDS); assertEquals(response.getResponseBody(), body); // twice Exception exception = null; try { c.preparePost(String.format("http://localhost:%d/foo/test", port2)).setBody(body).execute().get(TIMEOUT, TimeUnit.SECONDS); fail("Should throw exception. Too many connections issued."); } catch (Exception ex) { ex.printStackTrace(); exception = ex; } assertNotNull(exception); throw exception.getCause(); } }
@Test public void negativeContentTypeTest() throws Exception { AsyncHttpClientConfig config = config() .setConnectTimeout(100) .setMaxConnections(50) .setRequestTimeout(5 * 60 * 1000) // 5 minutes .build(); try (AsyncHttpClient client = asyncHttpClient(config)) { RequestBuilder requestBuilder = post(getTargetUrl()) .setHeader("Content-Type", "message/rfc822") .setBody(new InputStreamBodyGenerator(new ByteArrayInputStream(MY_MESSAGE.getBytes()))); Future<Response> future = client.executeRequest(requestBuilder.build()); System.out.println("waiting for response"); Response response = future.get(); assertEquals(response.getStatusCode(), 200); assertEquals(response.getResponseBody(), MY_MESSAGE); } } }
private DefaultAsyncHttpClientConfig.Builder httpClientBuilder() { return config() .setKeepAlive(true) .setMaxConnectionsPerHost(1) .setMaxConnections(1) .setConnectTimeout(1000) .setRequestTimeout(1000) .setFollowRedirect(true); }
public Builder setConnectTimeout(int connectTimeuot) { configBuilder.setConnectTimeout(connectTimeuot); return this; }