https://hc.apache.org/index.html
配置依赖
implementation group: 'org.apache.httpcomponents', name: 'httpclient', version: '4.5.13'
implementation group: 'org.apache.httpcomponents', name: 'httpcore', version: '4.4.12'
implementation group: 'org.apache.httpcomponents', name: 'httpasyncclient', version: '4.1.4'
implementation group: 'org.apache.httpcomponents', name: 'httpcore-nio', version: '4.4.12'
var credProvider = new BasicCredentialsProvider();
credProvider.setCredentials(
new AuthScope(host, port),
new UsernamePasswordCredentials(username, password));
var connManager = new PoolingHttpClientConnectionManager();
connManager.setMaxTotal(100);
connManager.setDefaultMaxPerRoute(100);
connManager.setValidateAfterInactivity(3000);
var requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(1000)
.setConnectTimeout(2000)
.setSocketTimeout(3000)
.build();
var httpClient = HttpClients.custom()
.setDefaultCredentialsProvider(credProvider)
.setConnectionManager(connManager)
.setDefaultRequestConfig(requestConfig)
.evictExpiredConnections()
.evictIdleConnections(180, TimeUnit.SECONDS)
.build();
参数配置说明:
httpclient支持连接池化, 在进行http请求的时候, 需要建立tcp连接, 要经过三次握手, 所以为了复用tcp连接, 就需要池化连接, 池化连接是针对HttpHost
这个类的(由connMgr.setMaxPerRoute()的参数是HttpHost类型可知)的, 既可以是ip:port, 也可以是hostname:port. 如果是后者, 则这一整个域名背后所有的ip共享一个route的limit限制.
setMaxTotal
: 设置一共可以建立的连接个数, 过多的会造成被访问节点的负担, 过少影响请求方的效率
setDefaultMaxPerRoute
: 设置每个route默认的最大连接数
setMaxPerRoute(HttpHost, Integer)
: 可以覆盖default值, 为某个route设置连接数
setConnectionRequestTimeout
: 从连接池获取连接超时
setConnectTimeout
: 连接超时
setSocketTimeout
: 读超时
参考:
https://www.cnblogs.com/trust-freedom/p/6349502.html
https://blog.csdn.net/wujun2412/article/details/120704886
感谢分享
网友评论