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/" ));
   }
}
这样问题就完美解决了

转载于:https://www.cnblogs.com/hugo-zhangzhen/p/6858013.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值