Httpclient4.5详解之源码解析和使用二: 连接池内连接的创建 借出 归还
接上篇文章我们分析了连接池内连接的创建 借出和归还,在归还那节中我们提到他是根据连接是长连接还是短连接来判断是关闭连接还是放回连接池保持连接,那么什么情况下为长连接,什么情况下又是短连接
MainClientExec#execute中获取到HttpResponse之后还有一个ConnectionReuseStrategy判定是否为长连接还是短连接的策略自行
//判断是否为长连接
if (reuseStrategy.keepAlive(response, context)) {
// Set the idle duration of this connection
//获取到响应头中timeout的值,若未获取到返回-1
final long duration = keepAliveStrategy.getKeepAliveDuration(response, context);
if (this.log.isDebugEnabled()) {
final String s;
if (duration > 0) {
s = "for " + duration + " " + TimeUnit.MILLISECONDS;
} else {
s = "indefinitely";
}
this.log.debug("Connection can be kept alive " + s);
}
connHolder.setValidFor(duration, TimeUnit.MILLISECONDS);
//reusable设置为true
connHolder.markReusable();
} else {
//reusable设置为false
connHolder.markNonReusable();
}
实现类为DefaultClientConnectionReuseStrategy 若请求头中包含Connection:Close返回false
@Override
public boolean keepAlive(final HttpResponse response, final HttpContext context) {
final HttpRequest request = (HttpRequest) context.getAttribute(HttpCoreContext.HTTP_REQUEST);
if (request