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