HttpClient:Timeout waiting for connection from pool

最近线上服务经常抛出如下异常:

org.apache.http.conn.ConnectionPoolTimeoutException: Timeout waiting for connection from pool

使用以下代码打出HttpClient连接池的状态:

Iterator iterator = poolingHttpClientConnectionManager.getRoutes().iterator();
while (iterator.hasNext()) {
    HttpRoute httpRoute = (HttpRoute) iterator.next();
    LOGGER.info(httpRoute.getTargetHost().getHostName() + poolingHttpClientConnectionManager.getStats(httpRoute));
}
LOGGER.info("---------------------totalStats:{}", poolingHttpClientConnectionManager.getTotalStats());
1.com[leased: 23; pending: 0; available: 2; max: 200]
2.com[leased: 0; pending: 0; available: 2; max: 200]
3.com[leased: 0; pending: 0; available: 2; max: 200]
---------------------totalStats:[leased: 23; pending: 0; available: 6; max: 600]

发现路由2.com和3.com处于正常状态,连接都能正常被release,但路由1.com的leased数量却只增不减,2、3与1有什么区别?
再看看tcp连接状态

# netstat -t | awk '/^tcp/ {++S[$NF]} END {for(a in S) print a, S[a]}'  
CLOSE_WAIT 27
ESTABLISHED 28
TIME_WAIT 4865

为何1.com的leased数量与CLOSE_WAIT数量如此接近?
看看代码,请求2.com和3.com用的是RestTemplate,而1.com因为当时遇到了url编码的问题,采用了如下方式:

try {
    BasicHttpRequest request = new BasicHttpRequest("GET", uri);
    HttpResponse response = httpClient.execute(TARGET, request);
    if (response.getStatusLine().getStatusCode() == HttpStatus.OK.value()) {
        String res = EntityUtils.toString(response.getEntity());
        Map result = JsonUtils.parse(res, Map.class);
        ...
    }
} catch (Exception e) {
    ...
} 

发起请求,响应码为200时处理,没问题!戳进源码看看

    // 原来 HttpResponse#getEntity() 有一步close
    // CloseableHttpResponseProxy#close()
    public void close() throws IOException {
        final HttpEntity entity = this.original.getEntity();
        EntityUtils.consume(entity);
    }
    // EntityUtils#consume()
    public static void consume(HttpEntity entity) throws IOException {
        if (entity != null) {
            if (entity.isStreaming()) {
                InputStream instream = entity.getContent();
                if (instream != null) {
                    instream.close();
                }
            }
        }
    }

原来HttpResponse#getEntity()时会释放资源,也就是将Entity消费掉!而上边代码中只有响应码为200时才会消费Entity,一旦响应码为非200时,资源没有关闭,连接得不到释放而转为CLOSE_WAIT状态,逐渐累积......
不敢想,解决问题先,把response.getEntity()代码提到响应码判断之前

HttpResponse response = httpClient.execute(TARGET, request);
String res = EntityUtils.toString(response.getEntity());
if (response.getStatusLine().getStatusCode() == HttpStatus.OK.value()) {
   ...
}

服务恢复正常!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,929评论 18 399
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,374评论 19 139
  • 1、TCP状态linux查看tcp的状态命令:1)、netstat -nat 查看TCP各个状态的数量2)、lso...
    北辰青阅读 13,167评论 0 11
  • 工作流程 一次HTTP操作称为一个事务,其工作过程可分为四步: 1)首先客户机与服务器需要建立连接。只要单击某个超...
    保川阅读 10,057评论 2 14
  • 世界上没有完美的人,如果有,请告诉我。——作者按 “短板理论”和“长板理论” 中国古语就有云:“尺有所短,寸有所长...
    瑶淼淼阅读 4,592评论 0 3