HttpClient 연결 풀 설정 및 사용

매번 새로운 HttpClient 대상 을 다시 만 들 면 동시 다발 로 올 라 올 때 이상 이 발생 하거나 연결 에 실패 하고 시간 을 초과 하기 쉽 습 니 다.HttpClient 의 연결 풀 설정 을 사용 하여 HttpClient 가 만 든 수량 을 줄 이 고 자원 비용 을 줄 일 수 있 습 니 다.package   com.mygame.common.utils;
  import   java.io.IOException; import   java.security.KeyManagementException; import   java.security.KeyStoreException; import   java.security.NoSuchAlgorithmException; import   org.apache.http.Header; 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.client.methods.HttpPost; 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.PlainConnectionSocketFactory; import   org.apache.http.conn.ssl.SSLConnectionSocketFactory; import   org.apache.http.conn.ssl.TrustSelfSignedStrategy; import   org.apache.http.entity.StringEntity; import   org.apache.http.impl.client.CloseableHttpClient; import   org.apache.http.impl.client.DefaultHttpRequestRetryHandler; import   org.apache.http.impl.client.HttpClients; import   org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import   org.apache.http.ssl.SSLContextBuilder; import   org.apache.http.util.EntityUtils; import   org.slf4j.Logger; import   org.slf4j.LoggerFactory; import   com.alibaba.fastjson.JSON;
  public   class   GameHttpClient {      private   static   Logger logger = LoggerFactory.getLogger(GameHttpClient. class );      //      private   static   PoolingHttpClientConnectionManager poolConnManager =  null ;
       private   static   CloseableHttpClient httpClient; // , http      static   {          try   {              System.out.println( " HttpClientTest~~~ " );              SSLContextBuilder builder =  new   SSLContextBuilder();              builder.loadTrustMaterial( null new   TrustSelfSignedStrategy());              SSLConnectionSocketFactory sslsf =  new   SSLConnectionSocketFactory(builder.build());              // HTTP HTPPS              Registry socketFactoryRegistry = RegistryBuilder.create().register( "http" , PlainConnectionSocketFactory.getSocketFactory()).register( "https" , sslsf).build();              //              poolConnManager =  new   PoolingHttpClientConnectionManager(socketFactoryRegistry);              poolConnManager.setMaxTotal( 640 ); //              //              poolConnManager.setDefaultMaxPerRoute( 320 );              // MaxtTotal DefaultMaxPerRoute :              // 1、MaxtTotal ;              // 2、DefaultMaxPerRoute MaxTotal ; :              // MaxtTotal=400 DefaultMaxPerRoute=200              // http://www.abc.com , 200; 400;              // http://www.bac.com              // http://www.ccd.com , 200; 400( 400); DefaultMaxPerRoute              // httpClient              httpClient = getConnection();
               System.out.println( " HttpClientTest~~~ " );          catch   (NoSuchAlgorithmException e) {              e.printStackTrace();          catch   (KeyStoreException e) {              e.printStackTrace();          catch   (KeyManagementException e) {              e.printStackTrace();          }      }
       public   static   CloseableHttpClient getConnection() {          RequestConfig config = RequestConfig.custom().setConnectTimeout( 5000 ).setConnectionRequestTimeout( 5000 ).setSocketTimeout( 5000 ).build();          CloseableHttpClient httpClient = HttpClients.custom()                  //                  .setConnectionManager(poolConnManager)                  .setDefaultRequestConfig(config)                  //                  .setRetryHandler( new   DefaultHttpRequestRetryHandler( 2 false )).build();          return   httpClient;      }             public   static   String httpGet(String url) {          HttpGet httpGet =  new   HttpGet(url);          CloseableHttpResponse response =  null ;                     try   {              response = httpClient.execute(httpGet);              String result = EntityUtils.toString(response.getEntity());              int   code = response.getStatusLine().getStatusCode();              if   (code == HttpStatus.SC_OK) {                  return   result;              else   {                  logger.error( " {} :{},{}" , url, code,result);                  return   null ;              }          catch   (IOException e) {              logger.error( "http ,{}" ,url,e);          finally   {              try   {                  if   (response !=  null )                      response.close();              catch   (IOException e) {                  e.printStackTrace();              }          }          return   null ;      }      public   static   String post(String uri, Object params, Header... heads) {          HttpPost httpPost =  new   HttpPost(uri);          CloseableHttpResponse response =  null ;          try   {              StringEntity paramEntity =  new   StringEntity(JSON.toJSONString(params));              paramEntity.setContentEncoding( "UTF-8" );              paramEntity.setContentType( "application/json" );              httpPost.setEntity(paramEntity);              if   (heads !=  null ) {                  httpPost.setHeaders(heads);              }               response = httpClient.execute(httpPost);              int   code = response.getStatusLine().getStatusCode();              String result = EntityUtils.toString(response.getEntity());              if   (code == HttpStatus.SC_OK) {                  return   result;              else   {                  logger.error( " {} :{}, :{},{}" , uri, code, params,result);                  return   null ;              }          catch   (IOException e) {              logger.error( " http " , e);          finally   {              try   {                 if (response !=  null ) {                     response.close();                 }              catch   (IOException e) {                  e.printStackTrace();              }          }          return   null ;      }
  }

좋은 웹페이지 즐겨찾기