HttpClient连接池出现连续ConnectionPoolTimeoutException:Timeout waiting for connection from pool异常

在写一个测试Demo的时候,需要重复请求api,来测试返回结果的正确性和服务器搜索的压力。
但是Demo执行几十次之后会无限的出现ConnectionPoolTimeoutException这个异常。
测试代码如下:

主程序

    public static void main(String[] args){
        String[] mountains = KeyWords.mountains.split(",");
        String[] keyWords = KeyWords.keyWord.split(",");
        HttpClient httpClient = HttpRequest.getHttpClient();

        for(int i = 0; i < loopNum; i++){
            for(String mountain : mountains){
                String jsonKey = searchKey.replace("$", mountain);
                byte[] bytesKey = null;
                String suffix = null;
                try {
                    bytesKey = Base64.encodeBase64(jsonKey.getBytes("UTF-8"));
                    suffix = new String(bytesKey, 0, bytesKey.length, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    System.out.println("MainTest.main:UnsupportedEncodingException!");
                }
                String httpUrl = url + suffix;
                HttpEntity entity = null;
                try {
                    entity = HttpClientFactory.httpGet(httpClient, httpUrl);    
                } catch(Exception e) {
                    System.out.println(httpUrl + ":" + e.getMessage());
                    continue;
                }
                System.out.println(httpUrl + ":" + entity.toString());
            }
        }
        System.out.println("Process complete!");
    }

HttpGet方法

    public static HttpEntity httpGet(final HttpClient httpClient, final String url) throws Exception
    {     
        HttpGet getReq = new HttpGet(url);
        getReq.setHeader("Accept-Encoding", "gzip");
        try {            
            getReq.setHeader("Connection", "close");
            HttpResponse response = httpClient.execute(getReq);
            return ParseResponse(response);
        } catch (Exception e) {
            getReq.releaseConnection();
            throw e;
        } 
    }

因为HttpClient是只有一个,在循环体内的只有HttpGet方法,所以问题肯定是在里面。
在网上查了之后知道是HttpGet如果不主动关闭的话是不会被销毁的。所以在方法结束之后返回之前要把HttpGet主动Abort。

修改之后的HttpGet方法

    public static HttpEntity httpGet(final HttpClient httpClient, final String url) throws Exception
    {     
        HttpGet getReq = new HttpGet(url);
        getReq.setHeader("Accept-Encoding", "gzip");
        try {            
            getReq.setHeader("Connection", "close");
            HttpResponse response = httpClient.execute(getReq);
            return ParseResponse(response);
        } catch (Exception e) {
            getReq.releaseConnection();
            throw e;
        } finally {
            getReq.abort();
        }
    }

修改之后就不会有问题了。

其他博客:
把手教你做自然语言理解智能对话的微信小程序【完整源码分享】

你可能感兴趣的:(开发)