转载自:
Http请求连接池-HttpClient的AbstractConnPool源码分析 - 天师符 - 博客园www.cnblogs.comHttp
底层是通过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;
默认