Apache PoolingHttpClientConnectionManager错误:连接池关闭

时间:2017-12-13 05:42:25

标签: java apache-httpclient-4.x

我使用这些方法从连接池中获取HttpClient:

public static final PoolingHttpClientConnectionManager connManager;

    public void initConnectionMnager() {
        HttpHost httpHost = new HttpHost("localhost");
        connManager = new PoolingHttpClientConnectionManager();
        connManager.setMaxTotal(200);
        connManager.setDefaultMaxPerRoute(50);
        connManager.setMaxPerRoute(new HttpRoute(httpHost),50);
        IdleConnectionMonitorThread staleMonitor
                = new IdleConnectionMonitorThread(connManager);
        staleMonitor.start();
    }

    public static CloseableHttpClient getHttpClient() {
        initConnectionMnager();
        RequestConfig requestConfig = RequestConfig.custom()
              .setConnectionRequestTimeout(servicesRequestTimeoutInMilliseconds)
                .setSocketTimeout(SOCKET_TIMEOUT_IN_MILLIS)
                .setConnectTimeout(servicesRequestTimeoutInMilliseconds)
                .build();
        HttpRequestRetryHandler retryHandler = new DefaultHttpRequestRetryHandler(3, false);
        return HttpClients
                .custom()
                .setConnectionManager(connManager)
                .setConnectionManagerShared(true)
                .setDefaultRequestConfig(requestConfig)
                .setRetryHandler(retryHandler)
                .setKeepAliveStrategy(getKeepAliveStrategy())
                .disableRedirectHandling()
                .build();
    }

    private static ConnectionKeepAliveStrategy getKeepAliveStrategy() {
        return (response, 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_HEADER)) {
                    return Long.parseLong(value) * 1000;
                }
            }
            return (long) servicesRequestTimeoutInMilliseconds;
        };
    }
}

但是我收到了这个错误:

java.lang.IllegalStateException: Connection pool shut down
    at org.apache.http.util.Asserts.check(Asserts.java:34)
    at org.apache.http.pool.AbstractConnPool.lease(AbstractConnPool.java:169)

有时会返回此错误(我确信我的服务器返回了正确的响应,并且在不使用连接池的情况下得到了正确的响应):

org.apache.http.NoHttpResponseException: 192.168.1.2 failed to responed

另外,我使用apache HttpClient 4.5.2。

0 个答案:

没有答案