• 72427

    文章

  • 659

    评论

  • 17

    友链

  • 最近新加了换肤功能,大家多来逛逛吧~~~~
  • 喜欢这个网站的朋友可以加一下QQ群,我们一起交流技术。

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;
	}
}
```

695856371Web网页设计师②群 | 喜欢本站的朋友可以收藏本站,或者加入我们大家一起来交流技术!

欢迎来到梁钟霖个人博客网站。本个人博客网站提供最新的站长新闻,各种互联网资讯。 还提供个人博客模板,最新最全的java教程,java面试题。在此我将尽我最大所能将此个人博客网站做的最好! 谢谢大家,愿大家一起进步!

转载原创文章请注明出处,转载至: 梁钟霖个人博客www.liangzl.com

0条评论

Loading...


发表评论

电子邮件地址不会被公开。 必填项已用*标注

自定义皮肤
注册梁钟霖个人博客