Httpclient4.5详解之源码解析和使用三: KeepAliveStrategy长连接还是短连接的判断

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
  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值