Java Apache PoollightTPClientConnection管理器在响应实体变为null时释放连接
我正在使用ApacheJava Apache PoollightTPClientConnection管理器在响应实体变为null时释放连接,java,web-services,apache-httpclient-4.x,Java,Web Services,Apache Httpclient 4.x,我正在使用Apachepoolighttpclientconnectionmanager将连接与ClosableHttpClient和CloseableHttpResponse一起进行服务调用。要读取服务器响应,我使用的是EntityUtils.consume(httpResponse.getEntity())。我想知道当httpResponse变为null时如何释放连接。我尝试了releaseConnection()(poollighttpclientconnectionmanager的方法)
poolighttpclientconnectionmanager
将连接与ClosableHttpClient
和CloseableHttpResponse
一起进行服务调用。要读取服务器响应,我使用的是EntityUtils.consume(httpResponse.getEntity())
。我想知道当httpResponse
变为null
时如何释放连接。我尝试了releaseConnection()
(poollighttpclientconnectionmanager的方法),但它不起作用。您可以在下面找到代码
String decision = "";
CloseableHttpResponse httpResponse = null;
try {
HttpPost requestPost = new HttpPost(endpoint1); requestPost.setHeader("Connection", "close");
requestPost.setHeader("Content-type",
"application/x-www-form-urlencoded");
requestPost.addHeader("Accept-Encoding", "gzip,deflate");
String xmlRequestStr = "Request=" + URLEncoder.encode(urlString);
String soRequest = xmlRequestStr;
requestPost.setEntity(new StringEntity(soRequest));
httpResponse = client.execute(requestPost);
decision = EntityUtils.toString(httpResponse.getEntity(),encod);
//connEvictor.shutdown();
} catch (Exception e) {
System.out.println("Pooling Connection manager Exception : " + e.getMessage());
e.printStackTrace();
//connEvictor.shutdown();
throw new ToolkitException("Connection Manager Exception", e.getMessage());
} finally {
EntityUtils.consume(httpResponse.getEntity());
httpResponse.close();
}
CloseableHttpClient
不应返回空响应。On errors应引发异常,因此可以安全地调用close()
。看
不要调用EntityUtils.consume(httpResponse.getEntity())因为如果发生错误,close
方法将不会执行,所以在finally
子句中使用code>
请阅读中的连接退出策略。您可以实施监视器来关闭服务器上已被阻止或关闭的过期和空闲连接。当请求超时且在httpResponse=client.execute(requestPost)中失败时,监视器调用closeExpiredConnections()
和closeIdleConnections(期间CloseableHttpClient返回null;步骤并转到异常块,我猜如果发生错误,它将通过异常块到达最终块。如果我保留EntityUtils.consume(httpResponse.getEntity());在try block中,当异常发生时,它将无法释放连接。对吗?如果我错了,请更正我。如果由于引发异常而导致响应为空,则您不必关闭或使用它。如果我离开它,则它将关闭\u等待TCP/IP状态。CloseableHttpClient可以重用。如果不需要,请释放资源需要它调用client.close()
为什么要关闭连接?请阅读docpoollighttpclientconnectionmanager
连接是基于每个路由进行池化的。在同一路由中需要资源之前,管理器可能会保持连接打开。您能否将路由的最大资源限制为1,并查看后续请求是否正在使用该连接什么?