HttpClient Connection Pool

Source: Internet
Author: User

 PackageCn.com.cfets.imt.impl.spring.util;Importorg.apache.http.HeaderElement;ImportOrg.apache.http.HeaderElementIterator;ImportOrg.apache.http.HttpResponse;Importorg.apache.http.client.ClientProtocolException;ImportOrg.apache.http.client.config.RequestConfig;ImportOrg.apache.http.client.methods.HttpGet;ImportOrg.apache.http.client.methods.HttpPost;Importorg.apache.http.client.methods.HttpRequestBase;ImportOrg.apache.http.conn.ConnectionKeepAliveStrategy;Importorg.apache.http.entity.ByteArrayEntity;Importorg.apache.http.impl.client.CloseableHttpClient;Importorg.apache.http.impl.client.HttpClients;ImportOrg.apache.http.impl.conn.PoolingHttpClientConnectionManager;ImportOrg.apache.http.message.BasicHeaderElementIterator;ImportOrg.apache.http.protocol.HTTP;ImportOrg.apache.http.protocol.HttpContext;ImportOrg.slf4j.Logger;Importorg.slf4j.LoggerFactory;Importorg.springframework.util.StringUtils;Importjava.io.IOException;ImportJava.net.URI;Importjava.net.URISyntaxException;ImportJava.net.URL;ImportJava.util.Map;/*** Connection Pool * Created by fenglei.ma on 2018/5/23.17:54*/ Public classHttpclientutils {Private Static FinalLogger log = Loggerfactory.getlogger (httpclientutils.class);  Public Static intConnect_time = 3 * 1000;  Public Static intSocket_time = 3 * 1000;//milliseconds     Public Static intRequest_time = 3 * 1000; //whether to re-connect     Public StaticString isreconn = "N"; //this is used to increase throughput by using connection pooling to prevent high concurrent large requests     Public StaticPoolinghttpclientconnectionmanager cm =NULL; //Use the default HttpClient instance.     Public StaticCloseablehttpclient httpClient =NULL; //maximum number of connections per route    Private Static Final intCount = 32; //maximum number of connections for the entire connection pool    Private Static Final intTotalCount = 500; Private Static Final intHttp_default_keep_time =15000;  Public Static synchronized voidInitpools () {if(HttpClient = =NULL) {cm=NewPoolinghttpclientconnectionmanager ();            Cm.setdefaultmaxperroute (count);            Cm.setmaxtotal (TotalCount); //Disable redirection setredirectsenabled (boolean.false)            if("Y". Equalsignorecase (Isreconn)) {httpClient=Httpclients.custom (). Setdefaultrequestconfig (Requestconfig.custom (). setredirectsenabled (Boole An.            FALSE). Build ()). Setkeepalivestrategy (Defaultstrategy). Setconnectionmanager (CM). Build (); }Else if("N". Equalsignorecase (isreconn) | |Stringutils.isempty (Isreconn)) {                /*** automaticretriesdisabled Type is Boolean, default value is False, * set to True here, disable retry Connection 3 times */httpClient=Httpclients.custom (). Setdefaultrequestconfig (Requestconfig.custom (). setredirectsenabled (Boole An. FALSE). Build ()). Setkeepalivestrategy (Defaultstrategy). Setconnectionmanager (cm). Disableautomaticretries (). b            Uild (); }        }    }    /*** Configure timeout settings for requests *@paramHttprequestbase*/    Private Static voidconfig (httprequestbase httprequestbase) {requestconfig requestconfig=Requestconfig.custom (). Setconnectionrequesttimeout (Request_time). Setconnecttimeout (CO        nnect_time). SetSocketTimeout (Socket_time). build ();    Httprequestbase.setconfig (Requestconfig); }    /*** Http connection keepAlive Settings*/     Public StaticConnectionkeepalivestrategy Defaultstrategy =NewConnectionkeepalivestrategy () { Public Longgetkeepaliveduration (HttpResponse response, HttpContext context) {Headerelementiterator it=NewBasicheaderelementiterator (Response.headeriterator (HTTP.            conn_keep_alive)); intKeeptime =Http_default_keep_time;  while(It.hasnext ()) {headerelement He=it.nextelement (); String param=He.getname (); String value=He.getvalue (); if(Value! =NULL&& param.equalsignorecase ("timeout")) {                    Try {                        returnLong.parselong (value) * 1000; } Catch(Exception e) {log.error ("Format KeepAlive timeout exception, exception:" +e.tostring ()); }                }            }            returnKeeptime * 1000;    }    }; /*** Get Request *@paramPath Request URL *@paramJsonparam Request Parameters *@paramAllheader Request Header *@return     */     Public StaticHttpResponse executegetmothedrequest (string path, String Jsonparam, Map<string, string>Allheader) {HttpGet HttpGet=NULL; HttpResponse Response=NULL; Try {            if(!Stringutils.isempty (Jsonparam)) {Path= Path + "?" +Jsonparam;            Log.info (path); } URL URL=NewURL (path); Uri URI=NewURI (Url.getprotocol (),NULL, Url.gethost (), Url.getport (), Url.getpath (), Url.getquery (),NULL); HttpGet=NewHttpGet (URI); Httpget.setheader ("Content-type", "Application/json");  for(Map.entry<string, string>E:allheader.entryset ())            {Httpget.setheader (E.getkey (), E.getvalue ()); }            if(HttpClient = =NULL) {initpools ();            } config (httpget); Response=Httpclient.execute (HttpGet); } Catch(Exception e) {log.error (E.getmessage (), E); }        returnresponse; }    /*** Post Request *@paramURL Request URL *@paramBody Request Data *@paramParamjson Request Parameters *@paramAllheade Request message Header *@return     */     Public StaticHttpResponse executepostmothedrequest (String URL,byte[] body, String Paramjson, map<string, string>Allheade) {HttpPost HttpPost=NULL; HttpResponse Response=NULL; Try {            if(!Stringutils.isempty (Paramjson)) {URL= URL + "?" +Paramjson;            Log.info (URL); } HttpPost=Newhttppost (URL); //message Header             for(Map.entry<string, string>E:allheade.entryset ()) {//Httppost.setheader ("Content-type", "Application/json");Httppost.setheader (E.getkey (), E.getvalue ()); }            //include upload file data            if(!Stringutils.isempty (body)) {//Httppost.setheader ("Content-type", "Application/json");Httppost.setentity (Newbytearrayentity (body)); }            if(HttpClient = =NULL) {initpools ();            } config (httppost); Response=Httpclient.execute (HttpPost); if(Response.getstatusline (). Getstatuscode () >= 400) {Log.warn ("Failed:http Error code:" +response.getstatusline (). Getstatuscode ()); }        } Catch(Exception e) {log.error (E.getmessage (), E); }        returnresponse; }}

HttpClient Connection Pool

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.