HttpClient连接池管理器
public class HttpClientConnection {
private static PoolingHttpClientConnectionManager manager;
static {
SSLContextBuilder builder = new SSLContextBuilder();
try {
builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
SSLConnectionSocketFactory sslSf;
sslSf = new SSLConnectionSocketFactory(builder.build());
// 配置同时支持 HTTP 和 HTTPS
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register(AllConstant.HTTP, PlainConnectionSocketFactory.getSocketFactory())
.register(AllConstant.HTTPS, sslSf).build();
manager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
//设置最大连接数
manager.setMaxTotal(100);
//设置最大主机连接数
manager.setDefaultMaxPerRoute(10);
} catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
e.printStackTrace();
}
}
public static CloseableHttpClient getHttpClientConnection() {
//设置超时时间
RequestConfig requestconfig = RequestConfig.custom()
.setConnectTimeout(AllConstant.HTTP_CONNECT_TIME_OUT)
.setConnectionRequestTimeout(AllConstant.HTTP_CONNECTION_REQUEST_TIME_OUT)
.setSocketTimeout(AllConstant.HTTP_SOCKET_TIME_OUT).build();
return HttpClients.custom()
// 设置连接池管理
.setConnectionManager(manager)
.setDefaultRequestConfig(requestconfig)
// 设置重试次数
.setRetryHandler(new DefaultHttpRequestRetryHandler(AllConstant.RETRY_COUNT, false)).build();
}
}
Test
第一次从连接池获取HttpClient
第二次从连接池获取HttpClient