在上一篇文章里我们介绍了 httpclient 连接池对于 SSL 的支持,这里主要介绍连接池中的长连接。
根据以前文章, 对于httpclient 连接池中的池化对象 CpoolEntry 都是可以被复用的,这样在每次申请连接的时候都会从可用连接集合 available 中获取,避免每次都重新创建连接,提高了效率。关于连接池如何决定重用连接,以及连接 keep alive 保活多久的介绍,请参考这篇文章。池化对象 CpoolEntry 虽然重用了,但是里面真正的原始 socket 是长连接么?我们从使用 httpclient 的代码分析,一般使用 httpclient 的代码如下:
/*Application code*/
try {
CloseableHttpClient htttpClient = HttpClients.custom().build();
HttpGet getMethod = new HttpGet("https://www.baidu.com/");
CloseableHttpResponse response = htttpClient.execute(getMethod);
HttpEntity entitry = response.getEntity();
byte[] contentArray = EntityUtils.toByteArray(entitry);
} catch (Exception e) {
// TODO Handle Exception here
}
/*EntityUtils*/
public static byte[] toByteArray(final HttpEntity entity) throws IOException {
Args.notNull(entity, "Entity");
final InputStream inStream = entity.getContent();
if (inStream == null) {
return null;
}
try {
Args.check(entity.getContentLength() <= Integer.MAX_VALUE, "HTTP entity too large to be buffered in memory");
int capacity = (int)entity.getContentLength();
if (capacity < 0) {
capacity = DEFAULT_BUFFER_SIZE;
}
final ByteArrayBuffer buffer = new ByteArrayBuffer(capacity);
final byte[] tmp = new byte[DEFAULT_BUFFER_SIZE];
int l;
while((l = inStream.read(tmp)) != -1) {
buffer.append(tmp, 0, l);
}
return buffer.toByteArray();
} finally {
inStream.close();
}
}
根据以上分析,在 httpclient 中如果希望重用池化对象并且保持长连接,那么务必调用 EntityUtils 中的方法。如果不希望重用池化对象,不希望有长连接,那么请调用 CloseableHttpResponse 的 close() 方法。
对于使用长连接的情况下也有一些思考:
目前先写到这里,在下一篇文章里我们总结一下 httpclient 连接池的使用建议。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有