HttpClient優(yōu)化思路:
池化
長連接
httpclient和httpget復用
合理的配置參數(shù)(最大并發(fā)請求數(shù),各種超時時間,重試次數(shù))
異步
多讀源碼
1.背景
我們有個業(yè)務,會調(diào)用其他部門提供的一個基于http的服務,日調(diào)用量在千萬級別。使用了httpclient來完成業(yè)務。之前因為qps上不去,就看了一下業(yè)務代碼,并做了一些優(yōu)化,記錄在這里。
先對比前后:優(yōu)化之前,平均執(zhí)行時間是250ms;
優(yōu)化之后,平均執(zhí)行時間是80ms,降低了三分之二的消耗,容器不再動不動就報警線程耗盡了,清爽~
2.分析
項目的原實現(xiàn)比較粗略,就是每次請求時初始化一個httpclient,生成一個httpPost對象,執(zhí)行,然后從返回結(jié)果取出entity,保存成一個字符串,最后顯式關閉response和client。
我們一點點分析和優(yōu)化:
2.1 httpclient反復創(chuàng)建開銷
httpclient是一個線程安全的類,沒有必要由每個線程在每次使用時創(chuàng)建,全局保留一個即可。
2.2 反復創(chuàng)建tcp連接的開銷
tcp的三次握手與四次揮手兩大裹腳布過程,對于高頻次的請求來說,消耗實在太大。試想如果每次請求我們需要花費5ms用于協(xié)商過程,那么對于qps為100的單系統(tǒng),1秒鐘我們就要花500ms用于握手和揮手。又不是高級領導,我們程序員就不要搞這么大做派了,改成keep alive方式以實現(xiàn)連接復用!
2.3 重復緩存entity的開銷
原本的邏輯里,使用了如下代碼:
HttpEntityentity=httpResponse.getEntity(); Stringresponse=EntityUtils.toString(entity);
這里我們相當于額外復制了一份content到一個字符串里,而原本的httpResponse仍然保留了一份content,需要被consume掉,在高并發(fā)且content非常大的情況下,會消耗大量內(nèi)存。并且,我們需要顯式的關閉連接,ugly。
3.實現(xiàn)
按上面的分析,我們主要要做三件事:一是單例的client,二是緩存的?;钸B接,三是更好的處理返回結(jié)果。一就不說了,來說說二。
提到連接緩存,很容易聯(lián)想到數(shù)據(jù)庫連接池。httpclient4提供了一個PoolingHttpClientConnectionManager 作為連接池。接下來我們通過以下步驟來優(yōu)化:
3.1 定義一個keep alive strategy
關于keep-alive,本文不展開說明,只提一點,是否使用keep-alive要根據(jù)業(yè)務情況來定,它并不是靈丹妙藥。還有一點,keep-alive和time_wait/close_wait之間也有不少故事。
在本業(yè)務場景里,我們相當于有少數(shù)固定客戶端,長時間極高頻次的訪問服務器,啟用keep-alive非常合適
再多提一嘴,http的keep-alive 和tcp的KEEPALIVE不是一個東西?;氐秸?,定義一個strategy如下:
ConnectionKeepAliveStrategymyStrategy=newConnectionKeepAliveStrategy(){
@Override
publiclonggetKeepAliveDuration(HttpResponseresponse,HttpContextcontext){
HeaderElementIteratorit=newBasicHeaderElementIterator
(response.headerIterator(HTTP.CONN_KEEP_ALIVE));
while(it.hasNext()){
HeaderElementhe=it.nextElement();
Stringparam=he.getName();
Stringvalue=he.getValue();
if(value!=null&¶m.equalsIgnoreCase
("timeout")){
returnLong.parseLong(value)*1000;
}
}
return60*1000;//如果沒有約定,則默認定義時長為60s
}
};
3.2 配置一個PoolingHttpClientConnectionManager
PoolingHttpClientConnectionManagerconnectionManager=newPoolingHttpClientConnectionManager(); connectionManager.setMaxTotal(500); connectionManager.setDefaultMaxPerRoute(50);//例如默認每路由最高50并發(fā),具體依據(jù)業(yè)務來定
也可以針對每個路由設置并發(fā)數(shù)。
3.3 生成httpclient
httpClient=HttpClients.custom() .setConnectionManager(connectionManager) .setKeepAliveStrategy(kaStrategy) .setDefaultRequestConfig(RequestConfig.custom().setStaleConnectionCheckEnabled(true).build()) .build();
?
注意:使用setStaleConnectionCheckEnabled方法來逐出已被關閉的鏈接不被推薦。更好的方式是手動啟用一個線程,定時運行closeExpiredConnections 和closeIdleConnections方法,如下所示。
?
publicstaticclassIdleConnectionMonitorThreadextendsThread{
privatefinalHttpClientConnectionManagerconnMgr;
privatevolatilebooleanshutdown;
publicIdleConnectionMonitorThread(HttpClientConnectionManagerconnMgr){
super();
this.connMgr=connMgr;
}
@Override
publicvoidrun(){
try{
while(!shutdown){
synchronized(this){
wait(5000);
//Closeexpiredconnections
connMgr.closeExpiredConnections();
//Optionally,closeconnections
//thathavebeenidlelongerthan30sec
connMgr.closeIdleConnections(30,TimeUnit.SECONDS);
}
}
}catch(InterruptedExceptionex){
//terminate
}
}
publicvoidshutdown(){
shutdown=true;
synchronized(this){
notifyAll();
}
}
}
3.4 使用httpclient執(zhí)行method時降低開銷
這里要注意的是,不要關閉connection。
一種可行的獲取內(nèi)容的方式類似于,把entity里的東西復制一份:
res=EntityUtils.toString(response.getEntity(),"UTF-8"); EntityUtils.consume(response1.getEntity());
但是,更推薦的方式是定義一個ResponseHandler,方便你我他,不再自己catch異常和關閉流。在此我們可以看一下相關的源碼:
publicTexecute(finalHttpHosttarget,finalHttpRequestrequest, finalResponseHandler?extends?T>responseHandler,finalHttpContextcontext) throwsIOException,ClientProtocolException{ Args.notNull(responseHandler,"Responsehandler"); finalHttpResponseresponse=execute(target,request,context); finalTresult; try{ result=responseHandler.handleResponse(response); }catch(finalExceptiont){ finalHttpEntityentity=response.getEntity(); try{ EntityUtils.consume(entity); }catch(finalExceptiont2){ //Logthisexception.Theoriginalexceptionismore //importantandwillbethrowntothecaller. this.log.warn("Errorconsumingcontentafteranexception.",t2); } if(tinstanceofRuntimeException){ throw(RuntimeException)t; } if(tinstanceofIOException){ throw(IOException)t; } thrownewUndeclaredThrowableException(t); } //Handlingtheresponsewassuccessful.Ensurethatthecontenthas //beenfullyconsumed. finalHttpEntityentity=response.getEntity(); EntityUtils.consume(entity);//看這里看這里 returnresult; }
可以看到,如果我們使用resultHandler執(zhí)行execute方法,會最終自動調(diào)用consume方法,而這個consume方法如下所示:
publicstaticvoidconsume(finalHttpEntityentity)throwsIOException{ if(entity==null){ return; } if(entity.isStreaming()){ finalInputStreaminstream=entity.getContent(); if(instream!=null){ instream.close(); } } }
可以看到最終它關閉了輸入流。
4.其他
通過以上步驟,基本就完成了一個支持高并發(fā)的httpclient的寫法,下面是一些額外的配置和提醒:
4.1 httpclient的一些超時配置
CONNECTION_TIMEOUT是連接超時時間,SO_TIMEOUT是socket超時時間,這兩者是不同的。連接超時時間是發(fā)起請求前的等待時間;socket超時時間是等待數(shù)據(jù)的超時時間。
HttpParamsparams=newBasicHttpParams(); //設置連接超時時間 IntegerCONNECTION_TIMEOUT=2*1000;//設置請求超時2秒鐘根據(jù)業(yè)務調(diào)整 IntegerSO_TIMEOUT=2*1000;//設置等待數(shù)據(jù)超時時間2秒鐘根據(jù)業(yè)務調(diào)整 //定義了當從ClientConnectionManager中檢索ManagedClientConnection實例時使用的毫秒級的超時時間 //這個參數(shù)期望得到一個java.lang.Long類型的值。如果這個參數(shù)沒有被設置,默認等于CONNECTION_TIMEOUT,因此一定要設置。 LongCONN_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的重試次數(shù),默認是3次;當前是禁用掉(如果項目量不到,這個默認即可) httpClient.setHttpRequestRetryHandler(newDefaultHttpRequestRetryHandler(0,false));
4.2 如果配置了nginx的話,nginx也要設置面向兩端的keep-alive
現(xiàn)在的業(yè)務里,沒有nginx的情況反而比較稀少。nginx默認和client端打開長連接而和server端使用短鏈接。
注意client端的keepalive_timeout和keepalive_requests參數(shù),以及upstream端的keepalive參數(shù)設置,這三個參數(shù)的意義在此也不再贅述。
以上就是我的全部設置。通過這些設置,成功地將原本每次請求250ms的耗時降低到了80左右,效果顯著。
JAR包如下:
org.apache.httpcomponents httpclient 4.5.6
代碼如下:
//Basic認證 privatestaticfinalCredentialsProvidercredsProvider=newBasicCredentialsProvider(); //httpClient privatestaticfinalCloseableHttpClienthttpclient; //httpGet方法 privatestaticfinalHttpGethttpget; // privatestaticfinalRequestConfigreqestConfig; //響應處理器 privatestaticfinalResponseHandlerresponseHandler; //jackson解析工具 privatestaticfinalObjectMappermapper=newObjectMapper();
static{
System.setProperty("http.maxConnections","50");
System.setProperty("http.keepAlive","true");
//設置basic校驗
credsProvider.setCredentials(
newAuthScope(AuthScope.ANY_HOST,AuthScope.ANY_PORT,AuthScope.ANY_REALM),
newUsernamePasswordCredentials("",""));
//創(chuàng)建http客戶端
httpclient=HttpClients.custom()
.useSystemProperties()
.setRetryHandler(newDefaultHttpRequestRetryHandler(3,true))
.setDefaultCredentialsProvider(credsProvider)
.build();
//初始化httpGet
httpget=newHttpGet();
//初始化HTTP請求配置
reqestConfig=RequestConfig.custom()
.setContentCompressionEnabled(true)
.setSocketTimeout(100)
.setAuthenticationEnabled(true)
.setConnectionRequestTimeout(100)
.setConnectTimeout(100).build();
httpget.setConfig(reqestConfig);
//初始化response解析器
responseHandler=newBasicResponseHandler();
}
/*
*功能:返回響應
*@authorzhangdaquan
*@param[url]
*@returnorg.apache.http.client.methods.CloseableHttpResponse
*@exception
*/
publicstaticStringgetResponse(Stringurl)throwsIOException{
HttpGetget=newHttpGet(url);
Stringresponse=httpclient.execute(get,responseHandler);
returnresponse;
}
/*
*功能:發(fā)送http請求,并用net.sf.json工具解析
*@authorzhangdaquan
*@param[url]
*@returnorg.json.JSONObject
*@exception
*/
publicstaticJSONObjectgetUrl(Stringurl)throwsException{
try{
httpget.setURI(URI.create(url));
Stringresponse=httpclient.execute(httpget,responseHandler);
JSONObjectjson=JSONObject.fromObject(response);
returnjson;
}catch(IOExceptione){
e.printStackTrace();
}
returnnull;
}
/*
*功能:發(fā)送http請求,并用jackson工具解析
*@authorzhangdaquan
*@param[url]
*@returncom.fasterxml.jackson.databind.JsonNode
*@exception
*/
publicstaticJsonNodegetUrl2(Stringurl){
try{
httpget.setURI(URI.create(url));
Stringresponse=httpclient.execute(httpget,responseHandler);
JsonNodenode=mapper.readTree(response);
returnnode;
}catch(IOExceptione){
e.printStackTrace();
}
returnnull;
}
/*
*功能:發(fā)送http請求,并用fastjson工具解析
*@authorzhangdaquan
*@param[url]
*@returncom.fasterxml.jackson.databind.JsonNode
*@exception
*/
publicstaticcom.alibaba.fastjson.JSONObjectgetUrl3(Stringurl){
try{
httpget.setURI(URI.create(url));
Stringresponse=httpclient.execute(httpget,responseHandler);
com.alibaba.fastjson.JSONObjectjsonObject=com.alibaba.fastjson.JSONObject.parseObject(response);
returnjsonObject;
}catch(IOExceptione){
e.printStackTrace();
}
returnnull;
}
審核編輯:湯梓紅
-
HTTP
+關注
關注
0文章
531瀏覽量
34820 -
源碼
+關注
關注
8文章
682瀏覽量
31062 -
代碼
+關注
關注
30文章
4940瀏覽量
73074 -
httpclient
+關注
關注
0文章
3瀏覽量
2047
原文標題:高并發(fā)場景下的 HttpClient 優(yōu)化方案,QPS 大大提升!
文章出處:【微信號:magedu-Linux,微信公眾號:馬哥Linux運維】歡迎添加關注!文章轉(zhuǎn)載請注明出處。
發(fā)布評論請先 登錄
【平頭哥RVB2601開發(fā)板試用體驗】基于 HTTPClient 的云語音識別 1
【平頭哥RVB2601開發(fā)板試用體驗】基于 HTTPClient 的云語音識別 2
如何去實現(xiàn)基于HTTPClient云語音識別的POST請求功能呢
在RVB2601上怎樣去實現(xiàn)基于HTTPClient組件的云語音識別呢
下載大文件使用HTTPClient和WiFiClient崩潰了怎么解決?
AT+HTTPCLIENT有沒有辦法打斷命令?
GPRS優(yōu)化思路總結(jié)報告
GPRS優(yōu)化思路總結(jié)報告_李青春
win10 uwp httpClient 登陸CSDN
VoLTE優(yōu)化思路干貨資料下載
日常網(wǎng)絡優(yōu)化思路資料下載
Web前端性能優(yōu)化思路

HttpClient優(yōu)化思路
評論