c++ 怎样连接两个链表_Http请求连接池-HttpClient的AbstractConnPool源码分析

转载自:

Http请求连接池-HttpClient的AbstractConnPool源码分析 - 天师符 - 博客园​www.cnblogs.com

Http底层是通过Tcp的三次握手建立连接的,若每个请求都要重新建立连接,那开销是很大的,特别是对于消息体非常小的场景,开销更大。

若使用连接池的方式,来管理连接对象,能极大地提高服务的吞吐量。

RestTemplate底层是封装了HttpClient(笔者的版本是4.3.6),它提供了连接池机制来处理高并发网络请求。

示例

通常,我们采用如下的样板代码来构建HttpClient:

HttpClientBuilder builder = HttpClientBuilder.create();
    builder.setMaxConnTotal(maxConnections).setMaxConnPerRoute(maxConnectionsPerRoute);
    if (!connectionReuse) {
    
        builder.setConnectionReuseStrategy(NoConnectionReuseStrategy.INSTANCE);
    }
    if (!automaticRetry) {
    
        builder.disableAutomaticRetries();
    }
    if (!compress) {
    
        builder.disableContentCompression();
    }
    HttpClient httpClient = builder.build();

从上面的代码可以看出,HttpClient使用建造者设计模式来构造对象,最后一行代码构建对象,前面的代码是用来设置客户端的最大连接数、单路由最大连接数、是否使用长连接、压缩等特性。

源码分析

我们进入HttpClientBuilder的build()方法,会看到如下代码:

# 构造Http连接池管理器
final PoolingHttpClientConnectionManager poolingmgr = 
             new PoolingHttpClientConnectionManager(
            RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", sslSocketFactory)
                .build());
    if (defaultSocketConfig != null) {
    
        poolingmgr.setDefaultSocketConfig(defaultSocketConfig);
    }
    if (defaultConnectionConfig != null) {
    
        poolingmgr.setDefaultConnectionConfig(defaultConnectionConfig);
    }
    if (systemProperties) {
    
        String s = System.getProperty("http.keepAlive", "true");
        if ("true".equalsIgnoreCase(s)) {
    
            s = System.getProperty("http.maxConnections", "5");
            final int max = Integer.parseInt(s);
            poolingmgr.setDefaultMaxPerRoute(max);
            poolingmgr.setMaxTotal(2 * max);
        }
    }
    if (maxConnTotal > 0) {
    
        poolingmgr.setMaxTotal(maxConnTotal);
    }
    if (maxConnPerRoute > 0) {
    
        poolingmgr.setDefaultMaxPerRoute(maxConnPerRoute);
    }
    # Http连接管理器采用连接池的方式实现
    connManager = poolingmgr;

默认

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值