httpclient连接池

在后台发送http请求时,每次都要经过三次握手的过程,这是一个比较耗时的操作且稳定性不好,经常连接失败。所以采用httpclient连接池,发起请求时直接从池里面获取连接,不用每次发起请求都经过三次握手,大大的提高的并发的效率。

1、maven依赖

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.2</version>
</dependency>
<dependency>
	<groupId>com.alibaba</groupId>
	<artifactId>fastjson</artifactId>
	<version>1.2.3</version>
</dependency>

2、http请求工具类

public class HttpJsonUtil {
	private static Logger logger = LoggerFactory.getLogger(HttpJsonUtil.class);
	// 默认超时时间:10s
	private static final int TIME_OUT = 10 * 1000; 
	private static PoolingHttpClientConnectionManager cm = null;
	static{
		LayeredConnectionSocketFactory sslsf = null;
		try{
			sslsf = new SSLConnectionSocketFactory(SSLContext.getDefault());
		}catch(NoSuchAlgorithmException e){
			logger.error("创建SSL连接失败...");
		}
		Registry<ConnectionSocketFactory> sRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
				.register("https", sslsf)
				.register("http", new PlainConnectionSocketFactory())
				.build();
		cm = new PoolingHttpClientConnectionManager(sRegistry);
		// 设置最大的连接数
		cm.setMaxTotal(200);
		// 设置每个路由的基础连接数【默认,每个路由基础上的连接不超过2个,总连接数不能超过20】
		cm.setDefaultMaxPerRoute(20);
	}	
	private static CloseableHttpClient getHttpClient(){
		CloseableHttpClient httpClient = HttpClients.custom()
				.setConnectionManager(cm).build();
		return httpClient;
	}
    /**
     * 发送get请求
     * @param url 路径
     * @return
     */
	public static JSONObject httpGet(String url) {
		JSONObject jsonResult = null;
		CloseableHttpClient httpClient = getHttpClient();
	        // get请求返回结果
		CloseableHttpResponse response = null;
		try {
			// 配置请求超时时间
        	RequestConfig requestConfig = RequestConfig.custom()  
        	        .setConnectTimeout(TIME_OUT).setConnectionRequestTimeout(TIME_OUT)  
        	        .setSocketTimeout(TIME_OUT).build();
			// 发送get请求
			HttpGet request = new HttpGet(url);
			request.setConfig(requestConfig);
			response = httpClient.execute(request);
			// 请求发送成功,并得到响应 
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				// 读取服务器返回过来的json字符串数据
				String strResult = EntityUtils.toString(response.getEntity());
				// 把json字符串转换成json对象
				jsonResult = JSONObject.parseObject(strResult);
				url = URLDecoder.decode(url, "UTF-8");
			} else {
				logger.error("get请求提交失败:" + url);
			}
		} catch (IOException e) {
			logger.error("get请求提交失败:" + url, e);
		} finally {
			if( response != null){
				try {
					EntityUtils.consume(response.getEntity());
					response.close();
				} catch (IOException e) {
					logger.error("关闭response失败:", e);
				}
			}
		}
		return jsonResult;
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值