org.apache.http.conn.ConnectionKeepAliveStrategy Java Examples
The following examples show how to use
org.apache.http.conn.ConnectionKeepAliveStrategy.
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: ApacheHttpClientConfig.java From sfg-blog-posts with GNU General Public License v3.0 | 6 votes |
@Bean public ConnectionKeepAliveStrategy connectionKeepAliveStrategy() { return (httpResponse, httpContext) -> { HeaderIterator headerIterator = httpResponse.headerIterator(HTTP.CONN_KEEP_ALIVE); HeaderElementIterator elementIterator = new BasicHeaderElementIterator(headerIterator); while (elementIterator.hasNext()) { HeaderElement element = elementIterator.nextElement(); String param = element.getName(); String value = element.getValue(); if (value != null && param.equalsIgnoreCase("timeout")) { return Long.parseLong(value) * 1000; // convert to ms } } return DEFAULT_KEEP_ALIVE_TIME; }; }
Example #2
Source File: HttpClient.java From data-prep with Apache License 2.0 | 6 votes |
/** * @return The connection keep alive strategy. */ private ConnectionKeepAliveStrategy getKeepAliveStrategy() { return (response, context) -> { // Honor 'keep-alive' header HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE)); while (it.hasNext()) { HeaderElement he = it.nextElement(); String param = he.getName(); String value = he.getValue(); if (value != null && "timeout".equalsIgnoreCase(param)) { try { return Long.parseLong(value) * 1000; } catch (NumberFormatException ignore) { // let's move on the next header value break; } } } // otherwise use the default value return defaultKeepAlive * 1000; }; }
Example #3
Source File: MockHttpClient.java From google-http-java-client with Apache License 2.0 | 6 votes |
@Override protected RequestDirector createClientRequestDirector( HttpRequestExecutor requestExec, ClientConnectionManager conman, ConnectionReuseStrategy reustrat, ConnectionKeepAliveStrategy kastrat, HttpRoutePlanner rouplan, HttpProcessor httpProcessor, HttpRequestRetryHandler retryHandler, RedirectHandler redirectHandler, AuthenticationHandler targetAuthHandler, AuthenticationHandler proxyAuthHandler, UserTokenHandler stateHandler, HttpParams params) { return new RequestDirector() { @Beta public HttpResponse execute(HttpHost target, HttpRequest request, HttpContext context) throws HttpException, IOException { return new BasicHttpResponse(HttpVersion.HTTP_1_1, responseCode, null); } }; }
Example #4
Source File: ApacheHttpClient.java From vespa with Apache License 2.0 | 6 votes |
static CloseableHttpClient makeCloseableHttpClient(Duration timeout, Duration keepAlive) { RequestConfig requestConfig = RequestConfig.custom() .setConnectTimeout((int) timeout.toMillis()) // establishment of connection .setConnectionRequestTimeout((int) timeout.toMillis()) // connection from connection manager .setSocketTimeout((int) timeout.toMillis()) // waiting for data .build(); ConnectionKeepAliveStrategy keepAliveStrategy = new DefaultConnectionKeepAliveStrategy() { @Override public long getKeepAliveDuration(HttpResponse response, HttpContext context) { long keepAliveMillis = super.getKeepAliveDuration(response, context); if (keepAliveMillis == -1) { keepAliveMillis = keepAlive.toMillis(); } return keepAliveMillis; } }; return VespaHttpClientBuilder.createWithBasicConnectionManager() .setUserAgent("service-monitor") .setKeepAliveStrategy(keepAliveStrategy) .disableAutomaticRetries() .setDefaultRequestConfig(requestConfig) .build(); }
Example #5
Source File: ClickHouseHttpClientBuilder.java From clickhouse-jdbc with Apache License 2.0 | 6 votes |
private ConnectionKeepAliveStrategy createKeepAliveStrategy() { return new ConnectionKeepAliveStrategy() { @Override public long getKeepAliveDuration(HttpResponse httpResponse, HttpContext httpContext) { // in case of errors keep-alive not always works. close connection just in case if (httpResponse.getStatusLine().getStatusCode() != HttpURLConnection.HTTP_OK) { return -1; } HeaderElementIterator it = new BasicHeaderElementIterator( httpResponse.headerIterator(HTTP.CONN_DIRECTIVE)); while (it.hasNext()) { HeaderElement he = it.nextElement(); String param = he.getName(); //String value = he.getValue(); if (param != null && param.equalsIgnoreCase(HTTP.CONN_KEEP_ALIVE)) { return properties.getKeepAliveTimeout(); } } return -1; } }; }
Example #6
Source File: HttpClientConfig.java From SpringBootBucket with MIT License | 6 votes |
@Bean public ConnectionKeepAliveStrategy connectionKeepAliveStrategy() { return new ConnectionKeepAliveStrategy() { @Override public long getKeepAliveDuration(HttpResponse response, HttpContext httpContext) { HeaderElementIterator it = new BasicHeaderElementIterator (response.headerIterator(HTTP.CONN_KEEP_ALIVE)); while (it.hasNext()) { HeaderElement he = it.nextElement(); String param = he.getName(); String value = he.getValue(); if (value != null && param.equalsIgnoreCase("timeout")) { return Long.parseLong(value) * 1000; } } return p.getDefaultKeepAliveTimeMillis(); } }; }
Example #7
Source File: HttpClientConfig.java From wecube-platform with Apache License 2.0 | 6 votes |
@Bean public ConnectionKeepAliveStrategy connectionKeepAliveStrategy() { return new ConnectionKeepAliveStrategy() { @Override public long getKeepAliveDuration(HttpResponse response, HttpContext context) { HeaderElementIterator it = new BasicHeaderElementIterator( response.headerIterator(HTTP.CONN_KEEP_ALIVE)); while (it.hasNext()) { HeaderElement he = it.nextElement(); String param = he.getName(); String value = he.getValue(); if (value != null && param.equalsIgnoreCase("timeout")) { return Long.parseLong(value) * 1000; } } return httpClientProperties.getDefaultKeepAliveTimeMillis(); } }; }
Example #8
Source File: ConnKeepAliveStrategy.java From xian with Apache License 2.0 | 5 votes |
public static ConnectionKeepAliveStrategy create(long keepTimeMill) { if (keepTimeMill < 0) throw new IllegalArgumentException("apache_httpclient连接持久时间不能小于0"); return new ConnectionKeepAliveStrategy() { public long getKeepAliveDuration(HttpResponse response, HttpContext context) { // Honor 'keep-alive' header HeaderElementIterator it = new BasicHeaderElementIterator( response.headerIterator(HTTP.CONN_KEEP_ALIVE)); while (it.hasNext()) { HeaderElement he = it.nextElement(); String param = he.getName(); String value = he.getValue(); if (value != null && param.equalsIgnoreCase("timeout")) { try { return Long.parseLong(value) * 1000; } catch (NumberFormatException ignore) { } } } return keepTimeMill; } }; }
Example #9
Source File: LibHttpClient.java From YiBo with Apache License 2.0 | 5 votes |
@Override protected RequestDirector createClientRequestDirector( final HttpRequestExecutor requestExec, final ClientConnectionManager conman, final ConnectionReuseStrategy reustrat, final ConnectionKeepAliveStrategy kastrat, final HttpRoutePlanner rouplan, final HttpProcessor httpProcessor, final HttpRequestRetryHandler retryHandler, final RedirectHandler redirectHandler, final AuthenticationHandler targetAuthHandler, final AuthenticationHandler proxyAuthHandler, final UserTokenHandler stateHandler, final HttpParams params) { return new LibRequestDirector( requestExec, conman, reustrat, kastrat, rouplan, httpProcessor, retryHandler, redirectHandler, targetAuthHandler, proxyAuthHandler, stateHandler, params); }
Example #10
Source File: HttpClientConnectionManagementLiveTest.java From tutorials with MIT License | 5 votes |
@Test // @Ignore // 5.1 public final void whenCustomizingKeepAliveStrategy_thenNoExceptions() throws ClientProtocolException, IOException { final ConnectionKeepAliveStrategy myStrategy = new ConnectionKeepAliveStrategy() { @Override public long getKeepAliveDuration(final HttpResponse myResponse, final HttpContext myContext) { final HeaderElementIterator it = new BasicHeaderElementIterator(myResponse.headerIterator(HTTP.CONN_KEEP_ALIVE)); while (it.hasNext()) { final HeaderElement he = it.nextElement(); final String param = he.getName(); final String value = he.getValue(); if ((value != null) && param.equalsIgnoreCase("timeout")) { return Long.parseLong(value) * 1000; } } final HttpHost target = (HttpHost) myContext.getAttribute(HttpCoreContext.HTTP_TARGET_HOST); if ("localhost".equalsIgnoreCase(target.getHostName())) { return 10 * 1000; } else { return 5 * 1000; } } }; client = HttpClients.custom().setKeepAliveStrategy(myStrategy).setConnectionManager(poolingConnManager).build(); client.execute(get1); client.execute(get2); }
Example #11
Source File: RestProtocol.java From dubbox with Apache License 2.0 | 4 votes |
protected <T> T doRefer(Class<T> serviceType, URL url) throws RpcException { if (connectionMonitor == null) { connectionMonitor = new ConnectionMonitor(); } // TODO more configs to add PoolingClientConnectionManager connectionManager = new PoolingClientConnectionManager(); // 20 is the default maxTotal of current PoolingClientConnectionManager connectionManager.setMaxTotal(url.getParameter(Constants.CONNECTIONS_KEY, 20)); connectionManager.setDefaultMaxPerRoute(url.getParameter(Constants.CONNECTIONS_KEY, 20)); connectionMonitor.addConnectionManager(connectionManager); // BasicHttpContext localContext = new BasicHttpContext(); DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager); httpClient.setKeepAliveStrategy(new ConnectionKeepAliveStrategy() { public long getKeepAliveDuration(HttpResponse response, HttpContext context) { HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE)); while (it.hasNext()) { HeaderElement he = it.nextElement(); String param = he.getName(); String value = he.getValue(); if (value != null && param.equalsIgnoreCase("timeout")) { return Long.parseLong(value) * 1000; } } // TODO constant return 30 * 1000; } }); HttpParams params = httpClient.getParams(); // TODO currently no xml config for Constants.CONNECT_TIMEOUT_KEY so we directly reuse Constants.TIMEOUT_KEY for now HttpConnectionParams.setConnectionTimeout(params, url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT)); HttpConnectionParams.setSoTimeout(params, url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT)); HttpConnectionParams.setTcpNoDelay(params, true); HttpConnectionParams.setSoKeepalive(params, true); ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient/*, localContext*/); ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build(); clients.add(client); client.register(RpcContextFilter.class); for (String clazz : Constants.COMMA_SPLIT_PATTERN.split(url.getParameter(Constants.EXTENSION_KEY, ""))) { if (!StringUtils.isEmpty(clazz)) { try { client.register(Thread.currentThread().getContextClassLoader().loadClass(clazz.trim())); } catch (ClassNotFoundException e) { throw new RpcException("Error loading JAX-RS extension class: " + clazz.trim(), e); } } } // TODO protocol ResteasyWebTarget target = client.target("http://" + url.getHost() + ":" + url.getPort() + "/" + getContextPath(url)); return target.proxy(serviceType); }
Example #12
Source File: RestProtocol.java From dubbox-hystrix with Apache License 2.0 | 4 votes |
protected <T> T doRefer(Class<T> serviceType, URL url) throws RpcException { if (connectionMonitor == null) { connectionMonitor = new ConnectionMonitor(); } // TODO more configs to add PoolingClientConnectionManager connectionManager = new PoolingClientConnectionManager(); // 20 is the default maxTotal of current PoolingClientConnectionManager connectionManager.setMaxTotal(url.getParameter(Constants.CONNECTIONS_KEY, 20)); connectionManager.setDefaultMaxPerRoute(url.getParameter(Constants.CONNECTIONS_KEY, 20)); connectionMonitor.addConnectionManager(connectionManager); // BasicHttpContext localContext = new BasicHttpContext(); DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager); httpClient.setKeepAliveStrategy(new ConnectionKeepAliveStrategy() { public long getKeepAliveDuration(HttpResponse response, HttpContext context) { HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE)); while (it.hasNext()) { HeaderElement he = it.nextElement(); String param = he.getName(); String value = he.getValue(); if (value != null && param.equalsIgnoreCase("timeout")) { return Long.parseLong(value) * 1000; } } // TODO constant return 30 * 1000; } }); HttpParams params = httpClient.getParams(); // TODO currently no xml config for Constants.CONNECT_TIMEOUT_KEY so we directly reuse Constants.TIMEOUT_KEY for now HttpConnectionParams.setConnectionTimeout(params, url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT)); HttpConnectionParams.setSoTimeout(params, url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT)); HttpConnectionParams.setTcpNoDelay(params, true); HttpConnectionParams.setSoKeepalive(params, true); ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient/*, localContext*/); ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build(); clients.add(client); client.register(RpcContextFilter.class); for (String clazz : Constants.COMMA_SPLIT_PATTERN.split(url.getParameter(Constants.EXTENSION_KEY, ""))) { if (!StringUtils.isEmpty(clazz)) { try { client.register(Thread.currentThread().getContextClassLoader().loadClass(clazz.trim())); } catch (ClassNotFoundException e) { throw new RpcException("Error loading JAX-RS extension class: " + clazz.trim(), e); } } } // TODO protocol ResteasyWebTarget target = client.target("http://" + url.getHost() + ":" + url.getPort() + "/" + getContextPath(url)); return target.proxy(serviceType); }
Example #13
Source File: ApacheHttpClient.java From aws-sdk-java-v2 with Apache License 2.0 | 4 votes |
private ConnectionKeepAliveStrategy buildKeepAliveStrategy(AttributeMap standardOptions) { long maxIdle = standardOptions.get(SdkHttpConfigurationOption.CONNECTION_MAX_IDLE_TIMEOUT).toMillis(); return maxIdle > 0 ? new SdkConnectionKeepAliveStrategy(maxIdle) : null; }
Example #14
Source File: ApacheHttpClientFactory.java From ibm-cos-sdk-java with Apache License 2.0 | 4 votes |
private ConnectionKeepAliveStrategy buildKeepAliveStrategy(HttpClientSettings settings) { return settings.getMaxIdleConnectionTime() > 0 ? new SdkConnectionKeepAliveStrategy(settings.getMaxIdleConnectionTime()) : null; }
Example #15
Source File: HttpHelper.java From benten with MIT License | 4 votes |
@PostConstruct public void init() { poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager(); poolingHttpClientConnectionManager.setMaxTotal(maxTotalConnections); poolingHttpClientConnectionManager .setDefaultMaxPerRoute(this.maxConnectionsPerRoute); ConnectionKeepAliveStrategy myStrategy = new ConnectionKeepAliveStrategy() { public long getKeepAliveDuration(HttpResponse response, HttpContext context) { HeaderElementIterator it = new BasicHeaderElementIterator( response.headerIterator(HTTP.CONN_KEEP_ALIVE)); while (it.hasNext()) { HeaderElement he = it.nextElement(); String param = he.getName(); String value = he.getValue(); if (value != null && param.equalsIgnoreCase("timeout")) { try { return Long.parseLong(value) * 1000; } catch (NumberFormatException ignore) { } } } return keepAliveDurationMilliseconds; } }; RequestConfig.Builder requestConfigBuilder = RequestConfig.custom(); if (isProxyNeeded) { requestConfigBuilder.setProxy(new HttpHost(proxyHost, proxyPort)); } RequestConfig requestConfig = requestConfigBuilder .setConnectionRequestTimeout(this.connReqTimeoutMilliseconds) .setConnectTimeout(connTimeoutMilliseconds) .setSocketTimeout(this.socketTimeoutMilliseconds) .setStaleConnectionCheckEnabled(false) .setRedirectsEnabled(true).setMaxRedirects(maxRedirects) .build(); HttpClientBuilder builder = HttpClientBuilder.create() .setDefaultRequestConfig(requestConfig); httpClient = builder .setConnectionManager(poolingHttpClientConnectionManager) .setKeepAliveStrategy(myStrategy).build(); if (reapInterval > 0 && idleConnectionsTimeout > 0) { LOGGER.debug(String .format("Initializing idle connection monitor thread with reap interval %s ms and idle connection time out %s ms", reapInterval, idleConnectionsTimeout)); idcm = new IdleConnectionMonitorThread( poolingHttpClientConnectionManager, reapInterval, idleConnectionsTimeout); idcm.start(); } }
Example #16
Source File: RestProtocol.java From dubbox with Apache License 2.0 | 4 votes |
protected <T> T doRefer(Class<T> serviceType, URL url) throws RpcException { if (connectionMonitor == null) { connectionMonitor = new ConnectionMonitor(); } // TODO more configs to add PoolingClientConnectionManager connectionManager = new PoolingClientConnectionManager(); // 20 is the default maxTotal of current PoolingClientConnectionManager connectionManager.setMaxTotal(url.getParameter(Constants.CONNECTIONS_KEY, 20)); connectionManager.setDefaultMaxPerRoute(url.getParameter(Constants.CONNECTIONS_KEY, 20)); connectionMonitor.addConnectionManager(connectionManager); // BasicHttpContext localContext = new BasicHttpContext(); DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager); httpClient.setKeepAliveStrategy(new ConnectionKeepAliveStrategy() { public long getKeepAliveDuration(HttpResponse response, HttpContext context) { HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE)); while (it.hasNext()) { HeaderElement he = it.nextElement(); String param = he.getName(); String value = he.getValue(); if (value != null && param.equalsIgnoreCase("timeout")) { return Long.parseLong(value) * 1000; } } // TODO constant return 30 * 1000; } }); HttpParams params = httpClient.getParams(); // TODO currently no xml config for Constants.CONNECT_TIMEOUT_KEY so we directly reuse Constants.TIMEOUT_KEY for now HttpConnectionParams.setConnectionTimeout(params, url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT)); HttpConnectionParams.setSoTimeout(params, url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT)); HttpConnectionParams.setTcpNoDelay(params, true); HttpConnectionParams.setSoKeepalive(params, true); ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient/*, localContext*/); ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build(); clients.add(client); client.register(RpcContextFilter.class); for (String clazz : Constants.COMMA_SPLIT_PATTERN.split(url.getParameter(Constants.EXTENSION_KEY, ""))) { if (!StringUtils.isEmpty(clazz)) { try { client.register(Thread.currentThread().getContextClassLoader().loadClass(clazz.trim())); } catch (ClassNotFoundException e) { throw new RpcException("Error loading JAX-RS extension class: " + clazz.trim(), e); } } } // TODO protocol ResteasyWebTarget target = client.target("http://" + url.getHost() + ":" + url.getPort() + "/" + getContextPath(url)); return target.proxy(serviceType); }
Example #17
Source File: RestProtocol.java From dubbox with Apache License 2.0 | 4 votes |
protected <T> T doRefer(Class<T> serviceType, URL url) throws RpcException { if (connectionMonitor == null) { connectionMonitor = new ConnectionMonitor(); } // TODO more configs to add PoolingClientConnectionManager connectionManager = new PoolingClientConnectionManager(); // 20 is the default maxTotal of current PoolingClientConnectionManager connectionManager.setMaxTotal(url.getParameter(Constants.CONNECTIONS_KEY, 20)); connectionManager.setDefaultMaxPerRoute(url.getParameter(Constants.CONNECTIONS_KEY, 20)); connectionMonitor.addConnectionManager(connectionManager); // BasicHttpContext localContext = new BasicHttpContext(); DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager); httpClient.setKeepAliveStrategy(new ConnectionKeepAliveStrategy() { public long getKeepAliveDuration(HttpResponse response, HttpContext context) { HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE)); while (it.hasNext()) { HeaderElement he = it.nextElement(); String param = he.getName(); String value = he.getValue(); if (value != null && param.equalsIgnoreCase("timeout")) { return Long.parseLong(value) * 1000; } } // TODO constant return 30 * 1000; } }); HttpParams params = httpClient.getParams(); // TODO currently no xml config for Constants.CONNECT_TIMEOUT_KEY so we directly reuse Constants.TIMEOUT_KEY for now HttpConnectionParams.setConnectionTimeout(params, url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT)); HttpConnectionParams.setSoTimeout(params, url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT)); HttpConnectionParams.setTcpNoDelay(params, true); HttpConnectionParams.setSoKeepalive(params, true); ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient/*, localContext*/); ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build(); clients.add(client); client.register(RpcContextFilter.class); for (String clazz : Constants.COMMA_SPLIT_PATTERN.split(url.getParameter(Constants.EXTENSION_KEY, ""))) { if (!StringUtils.isEmpty(clazz)) { try { client.register(Thread.currentThread().getContextClassLoader().loadClass(clazz.trim())); } catch (ClassNotFoundException e) { throw new RpcException("Error loading JAX-RS extension class: " + clazz.trim(), e); } } } // TODO protocol ResteasyWebTarget target = client.target("http://" + url.getHost() + ":" + url.getPort() + "/" + getContextPath(url)); return target.proxy(serviceType); }
Example #18
Source File: HttpConnection.java From arangodb-java-driver with Apache License 2.0 | 4 votes |
private HttpConnection(final HostDescription host, final Integer timeout, final String user, final String password, final Boolean useSsl, final SSLContext sslContext, final ArangoSerialization util, final Protocol contentType, final Long ttl, final String httpCookieSpec) { super(); this.host = host; this.user = user; this.password = password; this.useSsl = useSsl; this.util = util; this.contentType = contentType; final RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder .create(); if (Boolean.TRUE == useSsl) { if (sslContext != null) { registryBuilder.register("https", new SSLConnectionSocketFactory(sslContext)); } else { registryBuilder.register("https", new SSLConnectionSocketFactory(SSLContexts.createSystemDefault())); } } else { registryBuilder.register("http", new PlainConnectionSocketFactory()); } cm = new PoolingHttpClientConnectionManager(registryBuilder.build()); cm.setDefaultMaxPerRoute(1); cm.setMaxTotal(1); final RequestConfig.Builder requestConfig = RequestConfig.custom(); if (timeout != null && timeout >= 0) { requestConfig.setConnectTimeout(timeout); requestConfig.setConnectionRequestTimeout(timeout); requestConfig.setSocketTimeout(timeout); } if (httpCookieSpec != null && httpCookieSpec.length() > 1) { requestConfig.setCookieSpec(httpCookieSpec); } final ConnectionKeepAliveStrategy keepAliveStrategy = (response, context) -> HttpConnection.this.getKeepAliveDuration(response); final HttpClientBuilder builder = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig.build()) .setConnectionManager(cm).setKeepAliveStrategy(keepAliveStrategy) .setRetryHandler(new DefaultHttpRequestRetryHandler()); if (ttl != null) { builder.setConnectionTimeToLive(ttl, TimeUnit.MILLISECONDS); } client = builder.build(); }
Example #19
Source File: RestProtocol.java From dubbo-2.6.5 with Apache License 2.0 | 4 votes |
@Override protected <T> T doRefer(Class<T> serviceType, URL url) throws RpcException { if (connectionMonitor == null) { connectionMonitor = new ConnectionMonitor(); } // TODO more configs to add PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(); // 20 is the default maxTotal of current PoolingClientConnectionManager 20是当前池化clientconnectionmanager的默认最大值 connectionManager.setMaxTotal(url.getParameter(Constants.CONNECTIONS_KEY, 20)); connectionManager.setDefaultMaxPerRoute(url.getParameter(Constants.CONNECTIONS_KEY, 20)); connectionMonitor.addConnectionManager(connectionManager); RequestConfig requestConfig = RequestConfig.custom() .setConnectTimeout(url.getParameter(Constants.CONNECT_TIMEOUT_KEY, Constants.DEFAULT_CONNECT_TIMEOUT)) .setSocketTimeout(url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT)) .build(); SocketConfig socketConfig = SocketConfig.custom() .setSoKeepAlive(true) .setTcpNoDelay(true) .build(); CloseableHttpClient httpClient = HttpClientBuilder.create() .setKeepAliveStrategy(new ConnectionKeepAliveStrategy() { @Override public long getKeepAliveDuration(HttpResponse response, HttpContext context) { HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE)); while (it.hasNext()) { HeaderElement he = it.nextElement(); String param = he.getName(); String value = he.getValue(); if (value != null && param.equalsIgnoreCase("timeout")) { return Long.parseLong(value) * 1000; } } // TODO constant return 30 * 1000; } }) .setDefaultRequestConfig(requestConfig) .setDefaultSocketConfig(socketConfig) .build(); ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient/*, localContext*/); ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build(); clients.add(client); client.register(RpcContextFilter.class); for (String clazz : Constants.COMMA_SPLIT_PATTERN.split(url.getParameter(Constants.EXTENSION_KEY, ""))) { if (!StringUtils.isEmpty(clazz)) { try { client.register(Thread.currentThread().getContextClassLoader().loadClass(clazz.trim())); } catch (ClassNotFoundException e) { throw new RpcException("Error loading JAX-RS extension class: " + clazz.trim(), e); } } } // TODO protocol ResteasyWebTarget target = client.target("http://" + url.getHost() + ":" + url.getPort() + "/" + getContextPath(url)); return target.proxy(serviceType); }
Example #20
Source File: LibRequestDirector.java From YiBo with Apache License 2.0 | 4 votes |
public LibRequestDirector( final HttpRequestExecutor requestExec, final ClientConnectionManager conman, final ConnectionReuseStrategy reustrat, final ConnectionKeepAliveStrategy kastrat, final HttpRoutePlanner rouplan, final HttpProcessor httpProcessor, final HttpRequestRetryHandler retryHandler, final RedirectHandler redirectHandler, final AuthenticationHandler targetAuthHandler, final AuthenticationHandler proxyAuthHandler, final UserTokenHandler userTokenHandler, final HttpParams params) { if (requestExec == null) { throw new IllegalArgumentException("Request executor may not be null."); } if (conman == null) { throw new IllegalArgumentException("Client connection manager may not be null."); } if (reustrat == null) { throw new IllegalArgumentException("Connection reuse strategy may not be null."); } if (kastrat == null) { throw new IllegalArgumentException("Connection keep alive strategy may not be null."); } if (rouplan == null) { throw new IllegalArgumentException("Route planner may not be null."); } if (httpProcessor == null) { throw new IllegalArgumentException("HTTP protocol processor may not be null."); } if (retryHandler == null) { throw new IllegalArgumentException("HTTP request retry handler may not be null."); } if (redirectHandler == null) { throw new IllegalArgumentException("Redirect handler may not be null."); } if (targetAuthHandler == null) { throw new IllegalArgumentException("Target authentication handler may not be null."); } if (proxyAuthHandler == null) { throw new IllegalArgumentException("Proxy authentication handler may not be null."); } if (userTokenHandler == null) { throw new IllegalArgumentException("User token handler may not be null."); } if (params == null) { throw new IllegalArgumentException("HTTP parameters may not be null"); } this.requestExec = requestExec; this.connManager = conman; this.reuseStrategy = reustrat; this.keepAliveStrategy = kastrat; this.routePlanner = rouplan; this.httpProcessor = httpProcessor; this.retryHandler = retryHandler; this.redirectHandler = redirectHandler; this.targetAuthHandler = targetAuthHandler; this.proxyAuthHandler = proxyAuthHandler; this.userTokenHandler = userTokenHandler; this.params = params; this.managedConn = null; this.execCount = 0; this.redirectCount = 0; this.maxRedirects = this.params.getIntParameter(ClientPNames.MAX_REDIRECTS, 100); this.targetAuthState = new AuthState(); this.proxyAuthState = new AuthState(); }