- public void init()
- {
- try {
- SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(null,
- new TrustSelfSignedStrategy())
- .build();
- HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
- SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
- sslcontext,hostnameVerifier);
- Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
- .register("http", PlainConnectionSocketFactory.getSocketFactory())
- .register("https", sslsf)
- .build();
- poolConnManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
- // Increase max total connection to 200
- poolConnManager.setMaxTotal(maxTotalPool);
- // Increase default max connection per route to 20
- poolConnManager.setDefaultMaxPerRoute(maxConPerRoute);
- SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(socketTimeout).build();
- poolConnManager.setDefaultSocketConfig(socketConfig);
- } catch (Exception e) {
- log.error("InterfacePhpUtilManager init Exception"+e.toString());
- }
- }
- public CloseableHttpClient getConnection()
- {
- RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(connectionRequestTimeout)
- .setConnectTimeout(connectTimeout).setSocketTimeout(socketTimeout).build();
- CloseableHttpClient httpClient = HttpClients.custom()
- .setConnectionManager(poolConnManager).setDefaultRequestConfig(requestConfig).build();
- if(poolConnManager!=null&&poolConnManager.getTotalStats()!=null)
- {
- log.info("now client pool "+poolConnManager.getTotalStats().toString());
- }
- return httpClient;
- }
- leased :the number of persistent connections tracked by the connection manager currently being used to execute requests.
- available :the number idle persistent connections.
- pending : the number of connection requests being blocked awaiting a free connection.
- max: the maximum number of allowed persistent connections.
需要特别关注pending和leased的值,如果
leased的值特别大,接近max,则需要修改max,如果pending的值也比较大,也需要调整max,并考虑设置timeout,可以设置两个timeout,一个是获取连接的timeout,另外一个是获取socket数据的timeout。代码中已经有相关示例了。