高併發場景下的 HttpClient 優化方案,QPS 大大提升!
HttpClient 優化思路:
-
池化
-
長連接
-
httpclient 和 httpget 複用
-
合理的配置參數(最大併發請求數,各種超時時間,重試次數)
-
異步
-
多讀源碼
-
背景
我們有個業務,會調用其他部門提供的一個基於 http 的服務,日調用量在千萬級別。使用了 httpclient 來完成業務。之前因爲 qps 上不去,就看了一下業務代碼,並做了一些優化,記錄在這裏。
先對比前後:優化之前,平均執行時間是 250ms;
優化之後,平均執行時間是 80ms,降低了三分之二的消耗,容器不再動不動就報警線程耗盡了,清爽~
- 分析
項目的原實現比較粗略,就是每次請求時初始化一個 httpclient,生成一個 httpPost 對象,執行,然後從返回結果取出 entity,保存成一個字符串,最後顯式關閉 response 和 client。
我們一點點分析和優化:
2.1 httpclient 反覆創建開銷
httpclient 是一個線程安全的類,沒有必要由每個線程在每次使用時創建,全局保留一個即可。
2.2 反覆創建 tcp 連接的開銷
tcp 的三次握手與四次揮手兩大裹腳布過程,對於高頻次的請求來說,消耗實在太大。試想如果每次請求我們需要花費 5ms 用於協商過程,那麼對於 qps 爲 100 的單系統,1 秒鐘我們就要花 500ms 用於握手和揮手。又不是高級領導,我們程序員就不要搞這麼大做派了,改成 keep alive 方式以實現連接複用!
2.3 重複緩存 entity 的開銷
原本的邏輯裏,使用瞭如下代碼:
HttpEntity entity = httpResponse.getEntity();
String response = EntityUtils.toString(entity);
這裏我們相當於額外複製了一份 content 到一個字符串裏,而原本的 httpResponse 仍然保留了一份 content,需要被 consume 掉,在高併發且 content 非常大的情況下,會消耗大量內存。並且,我們需要顯式的關閉連接,ugly。
- 實現
按上面的分析,我們主要要做三件事:一是單例的 client,二是緩存的保活連接,三是更好的處理返回結果。一就不說了,來說說二。
提到連接緩存,很容易聯想到數據庫連接池。httpclient4 提供了一個 PoolingHttpClientConnectionManager 作爲連接池。接下來我們通過以下步驟來優化:
3.1 定義一個 keep alive strategy
關於 keep-alive,本文不展開說明,只提一點,是否使用 keep-alive 要根據業務情況來定,它並不是靈丹妙藥。還有一點,keep-alive 和 time_wait/close_wait 之間也有不少故事。
在本業務場景裏,我們相當於有少數固定客戶端,長時間極高頻次的訪問服務器,啓用 keep-alive 非常合適
再多提一嘴,http 的 keep-alive 和 tcp 的 KEEPALIVE 不是一個東西。回到正文,定義一個 strategy 如下:
ConnectionKeepAliveStrategy myStrategy = new ConnectionKeepAliveStrategy() {
@Override
public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
HeaderElementIterator it = new BasicHeaderElementIterator
(response.headerIterator(HTTP.CONN_KEEP_ALIVE));
while (it.hasNext()) {
HeaderElement he = it.nextElement();
String param = he.getName();
String value = he.getValue();
if (value != null && param.equalsIgnoreCase
("timeout")) {
return Long.parseLong(value) * 1000;
}
}
return 60 * 1000;//如果沒有約定,則默認定義時長爲60s
}
};
3.2 配置一個 PoolingHttpClientConnectionManager
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
connectionManager.setMaxTotal(500);
connectionManager.setDefaultMaxPerRoute(50);//例如默認每路由最高50併發,具體依據業務來定
也可以針對每個路由設置併發數。
3.3 生成 httpclient
httpClient = HttpClients.custom()
.setConnectionManager(connectionManager)
.setKeepAliveStrategy(kaStrategy)
.setDefaultRequestConfig(RequestConfig.custom().setStaleConnectionCheckEnabled(true).build())
.build();
注意:使用 setStaleConnectionCheckEnabled 方法來逐出已被關閉的鏈接不被推薦。更好的方式是手動啓用一個線程,定時運行 closeExpiredConnections 和 closeIdleConnections 方法,如下所示。
public static class IdleConnectionMonitorThread extends Thread {
private final HttpClientConnectionManager connMgr;
private volatile boolean shutdown;
public IdleConnectionMonitorThread(HttpClientConnectionManager connMgr) {
super();
this.connMgr = connMgr;
}
@Override
public void run() {
try {
while (!shutdown) {
synchronized (this) {
wait(5000);
// Close expired connections
connMgr.closeExpiredConnections();
// Optionally, close connections
// that have been idle longer than 30 sec
connMgr.closeIdleConnections(30, TimeUnit.SECONDS);
}
}
} catch (InterruptedException ex) {
// terminate
}
}
public void shutdown() {
shutdown = true;
synchronized (this) {
notifyAll();
}
}
}
3.4 使用 httpclient 執行 method 時降低開銷
這裏要注意的是,不要關閉 connection。
一種可行的獲取內容的方式類似於,把 entity 裏的東西複製一份:
res = EntityUtils.toString(response.getEntity(),"UTF-8");
EntityUtils.consume(response1.getEntity());
但是,更推薦的方式是定義一個 ResponseHandler,方便你我他,不再自己 catch 異常和關閉流。在此我們可以看一下相關的源碼:
public <T> T execute(final HttpHost target, final HttpRequest request,
final ResponseHandler<? extends T> responseHandler, final HttpContext context)
throws IOException, ClientProtocolException {
Args.notNull(responseHandler, "Response handler");
final HttpResponse response = execute(target, request, context);
final T result;
try {
result = responseHandler.handleResponse(response);
} catch (final Exception t) {
final HttpEntity entity = response.getEntity();
try {
EntityUtils.consume(entity);
} catch (final Exception t2) {
// Log this exception. The original exception is more
// important and will be thrown to the caller.
this.log.warn("Error consuming content after an exception.", t2);
}
if (t instanceof RuntimeException) {
throw (RuntimeException) t;
}
if (t instanceof IOException) {
throw (IOException) t;
}
throw new UndeclaredThrowableException(t);
}
// Handling the response was successful. Ensure that the content has
// been fully consumed.
final HttpEntity entity = response.getEntity();
EntityUtils.consume(entity);//看這裏看這裏
return result;
}
可以看到,如果我們使用 resultHandler 執行 execute 方法,會最終自動調用 consume 方法,而這個 consume 方法如下所示:
public static void consume(final HttpEntity entity) throws IOException {
if (entity == null) {
return;
}
if (entity.isStreaming()) {
final InputStream instream = entity.getContent();
if (instream != null) {
instream.close();
}
}
}
可以看到最終它關閉了輸入流。
- 其他
通過以上步驟,基本就完成了一個支持高併發的 httpclient 的寫法,下面是一些額外的配置和提醒:
4.1 httpclient 的一些超時配置
CONNECTION_TIMEOUT 是連接超時時間,SO_TIMEOUT 是 socket 超時時間,這兩者是不同的。連接超時時間是發起請求前的等待時間;socket 超時時間是等待數據的超時時間。
HttpParams params = new BasicHttpParams();
//設置連接超時時間
Integer CONNECTION_TIMEOUT = 2 * 1000; //設置請求超時2秒鐘 根據業務調整
Integer SO_TIMEOUT = 2 * 1000; //設置等待數據超時時間2秒鐘 根據業務調整
//定義了當從ClientConnectionManager中檢索ManagedClientConnection實例時使用的毫秒級的超時時間
//這個參數期望得到一個java.lang.Long類型的值。如果這個參數沒有被設置,默認等於CONNECTION_TIMEOUT,因此一定要設置。
Long CONN_MANAGER_TIMEOUT = 500L; //在httpclient4.2.3中我記得它被改成了一個對象導致直接用long會報錯,後來又改回來了
params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, CONNECTION_TIMEOUT);
params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, SO_TIMEOUT);
params.setLongParameter(ClientPNames.CONN_MANAGER_TIMEOUT, CONN_MANAGER_TIMEOUT);
//在提交請求之前 測試連接是否可用
params.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, true);
//另外設置http client的重試次數,默認是3次;當前是禁用掉(如果項目量不到,這個默認即可)
httpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(0, false));
4.2 如果配置了 nginx 的話,nginx 也要設置面向兩端的 keep-alive
現在的業務裏,沒有 nginx 的情況反而比較稀少。nginx 默認和 client 端打開長連接而和 server 端使用短鏈接。
注意 client 端的 keepalive_timeout 和 keepalive_requests 參數,以及 upstream 端的 keepalive 參數設置,這三個參數的意義在此也不再贅述。
以上就是我的全部設置。通過這些設置,成功地將原本每次請求 250ms 的耗時降低到了 80 左右,效果顯著。
JAR 包如下:
<!-- httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.6</version>
</dependency>
代碼如下:
//Basic認證
private static final CredentialsProvider credsProvider = new BasicCredentialsProvider();
//httpClient
private static final CloseableHttpClient httpclient;
//httpGet方法
private static final HttpGet httpget;
//
private static final RequestConfig reqestConfig;
//響應處理器
private static final ResponseHandler<String> responseHandler;
//jackson解析工具
private static final ObjectMapper mapper = new ObjectMapper();
static {
System.setProperty("http.maxConnections","50");
System.setProperty("http.keepAlive", "true");
//設置basic校驗
credsProvider.setCredentials(
new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM),
new UsernamePasswordCredentials("", ""));
//創建http客戶端
httpclient = HttpClients.custom()
.useSystemProperties()
.setRetryHandler(new DefaultHttpRequestRetryHandler(3,true))
.setDefaultCredentialsProvider(credsProvider)
.build();
//初始化httpGet
httpget = new HttpGet();
//初始化HTTP請求配置
reqestConfig = RequestConfig.custom()
.setContentCompressionEnabled(true)
.setSocketTimeout(100)
.setAuthenticationEnabled(true)
.setConnectionRequestTimeout(100)
.setConnectTimeout(100).build();
httpget.setConfig(reqestConfig);
//初始化response解析器
responseHandler = new BasicResponseHandler();
}
/*
* 功能:返回響應
* @author zhangdaquan
* @param [url]
* @return org.apache.http.client.methods.CloseableHttpResponse
* @exception
*/
public static String getResponse(String url) throws IOException {
HttpGet get = new HttpGet(url);
String response = httpclient.execute(get,responseHandler);
return response;
}
/*
* 功能:發送http請求,並用net.sf.json工具解析
* @author zhangdaquan
* @param [url]
* @return org.json.JSONObject
* @exception
*/
public static JSONObject getUrl(String url) throws Exception{
try {
httpget.setURI(URI.create(url));
String response = httpclient.execute(httpget,responseHandler);
JSONObject json = JSONObject.fromObject(response);
return json;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/*
* 功能:發送http請求,並用jackson工具解析
* @author zhangdaquan
* @param [url]
* @return com.fasterxml.jackson.databind.JsonNode
* @exception
*/
public static JsonNode getUrl2(String url){
try {
httpget.setURI(URI.create(url));
String response = httpclient.execute(httpget,responseHandler);
JsonNode node = mapper.readTree(response);
return node;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/*
* 功能:發送http請求,並用fastjson工具解析
* @author zhangdaquan
* @param [url]
* @return com.fasterxml.jackson.databind.JsonNode
* @exception
*/
public static com.alibaba.fastjson.JSONObject getUrl3(String url){
try {
httpget.setURI(URI.create(url));
String response = httpclient.execute(httpget,responseHandler);
com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(response);
return jsonObject;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
作者:仰望星空的塵埃
來源:blog.csdn.net/u010285974/article/details/85696239
本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源:https://mp.weixin.qq.com/s/fsOt3IH9wV8aXeVqw_0b_A