How to actually close a specific connection from PoolingHttpClientConnectionManager

时间:2015-07-31 20:20:19

标签: apache-httpcomponents

we use the PoolingHttpClientConnectionManager through a LoadBalancer.

At some point in time the server returns a 500 (with a special message body), indicating the node can no longer service requests. At this point we need to tear down this persistent connection, and force the pool to re-establish a new one, which the LB will then connect to a new node that can service requests.

My question is once I get this response..how can we actually close the connection, and NOT return it back to the pool?

our code looks something like:

 ---
 cm = new PoolingHttpClientConnectionManager();
 cm.setDefaultConnectionConfig(ConnectionConfig.DEFAULT);
 cm.setDefaultMaxPerRoute(20);
 cm.setMaxTotal(20);
 httpClient = HttpClientBuilder.create()
                .setConnectionManager(cm)
                .setDefaultRequestConfig(reqConfig).build()
 -----

 HttpPut put = new HttpPut(path);
 put.setEntity(new StringEntity(body, ContentType.APPLICATION_JSON));
 try {
    resp = httpClient.execute(target.get(), httpUriRequest);
    httpResponse = new HttpResponse(resp,captureHeaders);
 } 
 finally { 
         put.releaseConnection();  // DOES NOT CLOSE CONNECTION, RETURNS IT TO POOL??
       if (resp != null) {
       try {
           resp.close();  // DOES NOT CLOSE CONNECTION, RETURNS IT THE POOL?
       } 
       catch(IOException e){
             logger.error("exception while closing resp", e);
       }
     }
 }

Thanks for any tips/pointers in advance :)

1 个答案:

答案 0 :(得分:0)

请勿使用HttpUriGet#releaseConnection()。它仅适用于HC 3.1兼容性。

使用HttpUriGet#abort()中止正在进行的请求执行并关闭基础连接,或者(推荐)CloseableHttpResponse#close,如果认为连接被重新使用或关闭,则保持连接活动(例如,如果有未响应的响应内容)。