Apache PoolingHttpClientConnectionManager抛出非法状态异常

时间:2014-09-17 11:56:28

标签: java connection-pooling apache-httpclient-4.x

以下是我如何使用它 -

private static final PoolingHttpClientConnectionManager connPool;

static {

        connPool = new PoolingHttpClientConnectionManager();
        // Increase max total connection to 200
        connPool.setMaxTotal(200);//configurable through app.properties
        // Increase default max connection per route to 50
        connPool.setDefaultMaxPerRoute(20);//configurable through app.properties

}

CloseableHttpClient httpClient = HttpClients.custom()
                .setConnectionManager(connPool) .build();

另外我在http GET附近放了一个finally块 -

finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                LOGGER.error(e.getMessage());   
            }
        }

这是我的stacktrace -

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)
    at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.requestConnection(PoolingHttpClientConnectionManager.java:217)
    at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:157)
    at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:194)
    at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:85)
    at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:108)
    at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:186)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:106)
    at com.A.B.C.CustomHttpClient.doGETAndValidate(CustomHttpClient.java:44)
    at com.A.B.C.SiteMonitorTask.monitorAndUpdateEndPoints(SiteMonitorTask.java:48)
    at com.A.B.C.SiteMonitorTask.run(SiteMonitorTask.java:37)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:744)

我正在使用Quartz来安排监控Http端点的工作。这是我的连接池配置

totalMaxHttpConn=200
maxHttpConnPerRoute=20

Maven依赖..神器版

httpclient 4.3.1
httpcore 4.3.1

编辑 - 通过不关闭finally块中的CloseableHttpClient来解决问题..任何人都可以告诉它为什么会这样? 如果关闭客户端,为什么连接池会关闭?

上面的closeablehttpclient是否是池的句柄而不是单个conn

2 个答案:

答案 0 :(得分:33)

在4.4版本中,方法setConnectionManagerShared被添加到HttpClientBuilder中。如果将其设置为true,则客户端将不会关闭连接管理器。

HttpClients.custom()
            .setConnectionManager(Util.getConnectionManager()) // shared connection manager
            .setConnectionManagerShared(true)

答案 1 :(得分:9)

此行为是由于HC 4.3中的错误造成的。它已在HC 4.4a1中修复。从4.4 CloseableHttpClient#close开始,只有在客户端专有的情况下才会自动关闭连接池