[英]HttpClient connection reusing with 4.3.x
我正在尝试使用 HttpClient 并且无法解读1.1.5的含义。 确保释放低级资源。
这些是如何解释关闭内容流和关闭响应的?
关闭内容流:(保持底层连接处于活动状态)
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpGet httpget = new HttpGet("http://localhost/");
// do multiple times on the same connection
for (...) {
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
try {
// do something useful
} finally {
EntityUtils.consume(entity); // <-- ensures reuse
}
}
}
} finally {
httpclient.close();
}
关闭响应:(立即关闭并丢弃连接)
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpGet httpget = new HttpGet("http://localhost/");
// do multiple times on different connections
for (...) {
ClosableHttpResponse response = httpclient.execute(httpget);
try {
HttpEntity entity = response.getEntity();
if (entity != null) {
// do something useful
}
} finally {
response.close(); // <-- ensures reconnect
}
}
} finally {
httpclient.close();
}
entityUtils.consume 为您关闭流...
if (entity.isStreaming()) {
final InputStream instream = entity.getContent();
if (instream != null) {
instream.close();
}
}
您只需将您的客户端“释放”回池中......
然后,您应该将 HttpClient 包装在一个可运行的...
public void run() {
handler.sendMessage(Message.obtain(handler, HttpConnection.DID_START));
CloseableHttpClient httpClient = HttpClients.custom()
.setConnectionManager(YourConnectionMgr.getInstance())
.addInterceptorLast(new HttpRequestInterceptor() {
public void process(
final HttpRequest request,
final HttpContext context) throws HttpException, IOException {
}
})
.build();
} //end runnable
在可运行结束时,客户端刚刚被释放回 ConnectionPool,您不必担心资源或清理。
使用扩展PoolingClientConnectionManager的管理器
newInstance = new MyConnectionManager(schemeRegistry);
instance.setMaxTotal(15);
instance.setDefaultMaxPerRoute(15);
HttpHost localhost = new HttpHost("api.parse.com", 443);
instance.setMaxPerRoute(new HttpRoute(localhost), 10);
最后,我认为您确实需要关闭池。
YourConnectionMgr.getInstance().shutdown();
YourConnectionMgr.reset();
更多细节在这里
一般来说,一旦你完成了你想要丢弃的实体,这样系统资源就不会被不再有意义的对象所束缚。 在我看来,这里唯一的区别是使用。 关于基础的那一章基本上就是在描述这一点。 无论您如何实施它,请确保仅在需要时使用资源。 低层资源是实体中的InputStream,高层资源是连接。 例如,如果您正在实施不需要读取完整 InputStream 来做出决定的内容,只需终止响应即可有效地为您处理清理工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.