使用PoolingHttpClientConnectionManager时需要释放连接

时间:2014-10-08 10:46:07

标签: rest http httpclient apache-httpclient-4.x

根据定义,PoolingHttpClientConnectionManager重用连接。如果是的话

1)不需要在?

后明确释放连接

2)如果发布,管理员将无法重用连接?

executing a method?

CloseableHttpClient closableHttpClient = HttpClients.custom().setConnectionManager(getPoolingHttpClientConnectionManager()).build();
        HttpPost post = new HttpPost(resourcePath);                    
                try {
                    return closableHttpClient.execute(post);

                } catch (IOException e) {
                   //handle exception
                }finally {
                    post.releaseConnection();
                }

2 个答案:

答案 0 :(得分:1)

(1)是的。连接管理器无法知道应用层是否已完成从租用连接读取。因此,必须将其明确释放回经理

(2)连接是否可以重复使用取决于几个因素:必须完全消耗响应消息,两端(客户端和服务器)必须表明他们保持连接活动的意图,没有i / o错误等等

答案 1 :(得分:1)

典型用例是:

CloseableHttpClient closableHttpClient = HttpClients.custom().setConnectionManager(getPoolingHttpClientConnectionManager()).build();
HttpGet httpget = new HttpGet("http://localhost/");
CloseableHttpResponse response = httpclient.execute(httpget);
try {
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        InputStream instream = entity.getContent();
        try {
            // do something useful
        } finally {
            instream.close();
        }
    }
} finally {
    response.close();
}
  1. 是的。 instream.close() response.close()将触发显式释放底层连接。这样称为release不会直接关闭套接字。它将检查几个事实: 1)如果流已完全消耗 2)如果重新设置了连接 3)如果对等服务器响应并保持活动

  2. closableHttpClient.close()将关闭连接池