类org.apache.http.conn.ConnectionKeepAliveStrategy源码实例Demo

下面列出了怎么用org.apache.http.conn.ConnectionKeepAliveStrategy的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: sfg-blog-posts   文件: ApacheHttpClientConfig.java
@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;
  };
}
 
源代码2 项目: wecube-platform   文件: HttpClientConfig.java
@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();
        }
    };
}
 
源代码3 项目: SpringBootBucket   文件: HttpClientConfig.java
@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();
        }
    };
}
 
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;
        }
    };
}
 
源代码5 项目: vespa   文件: ApacheHttpClient.java
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();
}
 
源代码6 项目: google-http-java-client   文件: MockHttpClient.java
@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);
    }
  };
}
 
源代码7 项目: data-prep   文件: HttpClient.java
/**
 * @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;
    };
}
 
源代码8 项目: xian   文件: ConnKeepAliveStrategy.java
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;
			}
		};
	}
 
源代码9 项目: YiBo   文件: LibHttpClient.java
@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);
}
 
@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);
}
 
源代码11 项目: dubbo-2.6.5   文件: RestProtocol.java
@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);
}
 
源代码12 项目: benten   文件: HttpHelper.java
@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();
    }
}
 
源代码13 项目: dubbox   文件: RestProtocol.java
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);
    }
 
源代码14 项目: dubbox-hystrix   文件: RestProtocol.java
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);
    }
 
源代码15 项目: aws-sdk-java-v2   文件: ApacheHttpClient.java
private ConnectionKeepAliveStrategy buildKeepAliveStrategy(AttributeMap standardOptions) {
    long maxIdle = standardOptions.get(SdkHttpConfigurationOption.CONNECTION_MAX_IDLE_TIMEOUT).toMillis();
    return maxIdle > 0 ? new SdkConnectionKeepAliveStrategy(maxIdle) : null;
}
 
源代码16 项目: ibm-cos-sdk-java   文件: ApacheHttpClientFactory.java
private ConnectionKeepAliveStrategy buildKeepAliveStrategy(HttpClientSettings settings) {
    return settings.getMaxIdleConnectionTime() > 0
            ? new SdkConnectionKeepAliveStrategy(settings.getMaxIdleConnectionTime())
            : null;
}
 
源代码17 项目: dubbox   文件: RestProtocol.java
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);
    }
 
源代码18 项目: dubbox   文件: RestProtocol.java
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);
    }
 
源代码19 项目: arangodb-java-driver   文件: HttpConnection.java
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();
}
 
源代码20 项目: YiBo   文件: LibRequestDirector.java
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();
}
 
 类所在包
 同包方法