httpclient鏈接池,解決後臺高併發的請求

在後臺發送http請求時,每次都要通過三次握手的過程,這是一個比較耗時的操做且穩定性很差,常常鏈接失敗。因此採用httpclient鏈接池,發起請求時直接從池裏面獲取鏈接,不用每次發起請求都通過三次握手,大大的提升的併發的效率
1.maven依賴java

<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請求工具類apache

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;
	}
}
```
相關文章
相關標籤/搜索