httpclient连接池,解决后台高并发的请求 - Go语言中文社区

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请求工具类

package com.litice.core.util;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSONObject;
import java.io.IOException;
import java.net.URLDecoder;
import java.security.NoSuchAlgorithmException;
import javax.net.ssl.SSLContext;
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;
	}
}
```

转载于:https://my.oschina.net/u/2489258/blog/1797151

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/weixin_34292287/article/details/92306444
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2020-03-07 15:15:56
  • 阅读 ( 1701 )
  • 分类:

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢