CloseableHttpClient 在使用過程中遇到的問題


代碼是前輩寫的,在對代碼進行壓測的時候遇到了個問題,最大線程是 不能超過setDefaultMaxPerRoute設置的數字,一點超過 就會死掉。這里會報錯 connection pool shut down httpclient

查找過很多博客,查到原因是因為接受到的集合沒有釋放導致  CloseableHttpClient 一直在被占用。隨意可使用的最線程數 就不會超過 之前設置setDefaultMaxPerRoute 數字

  private static CloseableHttpClienthttpClient;
  
   static {
     PoolingHttpClientConnectionManagercm = new PoolingHttpClientConnectionManager();
     cm.setMaxTotal( 200 );
     cm.setDefaultMaxPerRoute( 20 );
     cm.setDefaultMaxPerRoute( 50 );
     httpClient = HttpClients.custom().setConnectionManager(cm).build();
   }
  public static String get(String url) {
    HttpResponse response  = null;
     BufferedReaderin = null ;
     String result = "" ;
     try {
  
       HttpGethttpGet = new HttpGet(url);
       response = httpClient.execute(httpGet);
  
       in = new BufferedReader( new InputStreamReader(response.getEntity().getContent()));
       StringBuffersb = new StringBuffer( "" );
       String line = "" ;
       String NL = System.getProperty( "line.separator" );
       while ((line = in.readLine()) != null ) {
         sb.append(line + NL);
       }
       in.close();
       result = sb.toString();
     } catch (IOException e) {
       e.printStackTrace();
    
     return result;
   }
  
   public static void main(String[] args) {
     System.out.println(get( "https://www.baidu.com/" ));
   }
}
這里出現的錯誤就是 使用接受 httpClient.execute(httpGet); 的返回集合是錯誤的
應該使用 CloseableHttpResponse 並且需要關閉 接收到的返回結合
 
正確的寫法:
  public  static  String get(String url) {
    CloseableHttpResponse response  null;
     BufferedReaderin =  null ;
     String result =  "" ;
     try  {
  
       HttpGethttpGet =  new  HttpGet(url);
       response = httpClient.execute(httpGet);
  
       in =  new  BufferedReader( new  InputStreamReader(response.getEntity().getContent()));
       StringBuffersb =  new  StringBuffer( "" );
       String line =  "" ;
       String NL = System.getProperty( "line.separator" );
       while  ((line = in.readLine()) !=  null ) {
         sb.append(line + NL);
       }
       in.close();
       result = sb.toString();
     catch  (IOException e) {
       e.printStackTrace();
    
    finally {
      try {
        if (null != response) response.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
     return result;
   }
     return  result;
   }
  
   public  static  void  main(String[] args) {
     System.out.println(get( "https://www.baidu.com/" ));
   }
}
這樣問題就完美解決了


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM