httpclient 4.5.1---连接管理器

package com.cycore.dbs.common.util;


import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectionKeepAliveStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultConnectionKeepAliveStrategy;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.protocol.HttpContext;


/**
 * http客户端连接池管理类
 * @author xiawq
 *
 */
public class HCManager {



/**
* 连接池管理器
*/
private static PoolingHttpClientConnectionManager connManager 
= new PoolingHttpClientConnectionManager();
/**
* Http客户端
*/
private static CloseableHttpClient client = null;

/**
*请求配置 
*/
private static RequestConfig requestConfig = null;
static{
connManager.setDefaultMaxPerRoute(20);//为单路由设置默认最大并发连接数为50
if(requestConfig == null){
requestConfig=RequestConfig
.custom()
.setSocketTimeout(1000)
.setConnectTimeout(1000)
.build();
}
}
/**
* 自定义连接保持存活策略:如果响应头中有Keep-Alive相关的timeout设置,
* 则按Keep-Alive头中的timeout设定存活时间。不然默认为5秒。
*/
private static ConnectionKeepAliveStrategy connKeepAliveStrategy = 
new DefaultConnectionKeepAliveStrategy() {
@Override
public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
long keepAlive = super.getKeepAliveDuration(response, context);
if(keepAlive == -1){
keepAlive = 5*1000;
}
return keepAlive;
}
};

/**
* 获取http客户端
* @return
*/
protected static CloseableHttpClient getClient() {
if(client == null){
client = HttpClients.custom()
.setConnectionManager(connManager)
.setKeepAliveStrategy(connKeepAliveStrategy)
.build();
}
return client;
}

protected static RequestConfig getRequestConfig() {
return requestConfig;
}
}

你可能感兴趣的:(httpclient)