提问者:小点点

使用PoolingHttpClientConnectionManager时需要释放连接


根据定义,PoolingHttpClientConnectionManager重用连接。如果是这样

1)之后不需要显式释放连接?

2)如果释放,Manager将无法重用连接?

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个答案

匿名用户

典型用例是:

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();
}

>

  • 它是. instream.close()和response.close()将触发显式释放底层connection.Here所谓的释放不会直接关闭套接字。它将检查几个事实:1)如果流被完全消费2)如果连接被重用3)如果对等服务器响应与保持活动

    ClolableHttpClient. close()将关闭连接池

  • 匿名用户

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

    (2)连接是否可以重用取决于几个因素:响应消息必须被完全使用,两端(客户端和服务器)必须发出信号以保持连接存活,没有i/o错误等