1、pom添加内容
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpasyncclient</artifactId>
<version>4.1</version>
</dependency>
2、创建httpUtil
public class HttpUtil {
private static int socketTimeout = 1000;// 设置等待数据超时时间5秒钟 根据业务调整
private static int connectTimeout = 2000;// 连接超时
private static int poolSize = 100;// 连接池最大连接数
private static int maxPerRoute = 10;// 每个主机的并发最多10
/**
* 创建非异步的可关闭的且跳过https 验证的 httpClient
* @return
*/
public static CloseableHttpClient createSSLClientDefault() {
try {
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
}).build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
return HttpClients.custom().setSSLSocketFactory(sslsf).build();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
}
return HttpClients.createDefault();
}
/**
* 创建异步的可关闭的跳过https验证的 httpClient对象
* @param connManager 连接管理器 可以调用本类的getConnManager 生成
* @return
*/
public static CloseableHttpAsyncClient getClient(PoolingNHttpClientConnectionManager connManager) {
if (null == connManager) {
return null;
}
// 设置连接参数
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(HttpUtil.socketTimeout).setConnectTimeout(HttpUtil.connectTimeout).build();
// 创建自定义的httpclient对象
CloseableHttpAsyncClient client = HttpAsyncClients.custom().setDefaultRequestConfig(requestConfig)
.setConnectionManager(connManager).disableCookieManagement().build();
return client;
}
/**
* 创建异步的可关闭的跳过https验证的 httpClient对象(绑定本地网卡)
* @param connManager
* @param localAddress
* @return
* @throws
*/
public static CloseableHttpAsyncClient getClient(PoolingNHttpClientConnectionManager connManager, String localAddress) throws UnknownHostException {
if (null == connManager || null == localAddress) {
return null