PoolingHttpClientConnectionManager中的MaxPoolSize太小时,Apache的HttpClient停止工作

Gam*_*ids 2 java swingworker apache-httpclient-4.x

我有一个SwingWorker获取URL列表的列表(可以是数百个)。在该doInBackground()方法中,它遍历这些URL,每次创建a CloseableHttpClient,由a PoolingHttpClientConnectionManager和a管理HttpGet。然后,client将执行httpGet并将内容(图像)写入文件(如果可能!并非所有URL都有效,并且某些URL返回404)。

直到达到connectionManager 的maxTotal(或defaultMaxPerRoute),这大约可以处理100个请求。然后一切都停止了,客户端的执行停止了,并且没有抛出异常。

所以我想,我将maxTotal和设置defaultMaxPerRoute为1000并签出。当我尝试下载1500张图像时,它可以工作,但是感觉真不对劲!我想重用客户端,而不是在池中容纳1000个客户端。

Socket或ConnectionTimeouts无效,调试不会告诉我正在发生的事情,HttpClients而在没有该消息的情况下创建新指令PoolingHttpClientConnectionManager也不起作用。关闭客户端和/或结果也不起作用。

我应该如何管理客户端或设置池以确保我SwingWorker什至可以下载数千个图像?

我将尝试将SwingWorker代码分解为重要部分:(几乎忘了,它实际上是循环的对象列表,每个对象都有3个URL)

// this is how I init the connectionManager (outside the swing worker)
this.connectionManager = new PoolingHttpClientConnectionManager();
this.connectionManager.setMaxTotal(100);
this.connectionManager.setDefaultMaxPerRoute(100);

// this is where the images are downloaded in the swing worker
@Override
protected Void doInBackground() throws Exception{
    for(MyUrls myUrls : myUrlsList){
        client = HttpClients.custom().setConnectionManager(connectionManager).build();         
        for(MyImage image : myUrls.getImageList()){
            File outputFile = null;
            HttpEntity entity = null;
            switch(image.getImageSize()){
                case 1:
                    HttpGet httpGet = new HttpGet(image.getUrl()));
                    httpGet.setConfig(RequestConfig.custom().setSocketTimeout(1000).setConnectTimeout(1000).build());  // doesn't change anything
                    response = client.execute(httpGet);
                    if(response.getStatusLine().getStatusCode() >= 200 && response.getStatusLine().getStatusCode() < 300){
                        entity = response.getEntity();
                        if(entity != null){
                            String contentType = entity.getContentType().getValue();
                            String extension = "." + (contentType.contains("/") ? contentType.substring(contentType.indexOf("/") + 1) : "jpg");
                            outputFile = new File(image.getName()+extension);
                        }
                    }else{
                        System.err.println("download of "+image.getName()+extension+" failed: " + response.getStatusLine().getStatusCode());
                    }
                    break;
                case 2:
                   // the other cases are pretty much the same
            }
            if(entity != null && outputFile != null){
                try(InputStream inputStream = entity.getContent(); FileOutputStream outputStream = new FileOutputStream(outputFile)){
                    byte[] buffer = new byte[1024];
                    int bytesRead;
                    while((bytesRead = inputStream.read(buffer)) != -1){
                        outputStream.write(buffer, 0, bytesRead);
                    }
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

GPI*_*GPI 7

由于只有在您可以正确转储到文件输出流的OK响应(范围在200到300之间)时,才可以正确处理它们,因此可能会泄漏连接。

长话短说:始终处置实体

处置实体(响应对象的“内容”)是释放连接对象的唯一方法。为此,您可以在每个请求/响应周期的子句中调用EntityUtils.consume(responseEntity))和/或关闭响应对象(调用response.close())和/或关闭或读取实体的流(调用stream.close())finally。

您的代码实际上消耗了响应的流,但是仅在某些情况下(主要是:请求成功时)使用,因此这是对API的正确使用,而对于其他情况(例如404响应)则是不消耗或释放的。

您也可以ResponseHandler为此使用API变体,它将为您处理所有这些-我建议您使用它。

如果您不总是这样做,则HTTPClient会认为该连接处于活动状态,并且永远不会释放或重用该连接。在某个时候,您最终将获得一个空的连接池或一个系统错误(例如,打开了太多文件)。

请注意,它不仅适用于200 OK响应,还适用于每次调用(即使404通常具有响应正文,如果不使用该正文,则将不会释放连接)。

用户指南提示

我向您介绍了用户指南的“基础知识”部分:https : //hc.apache.org/httpcomponents-client-ga/tutorial/html/fundamentals.html

这是最简单形式的请求执行过程示例:

CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpget = new HttpGet("http://localhost/");
CloseableHttpResponse response = httpclient.execute(httpget);
try {
    <...>
} finally {
    response.close();
}
Run Code Online (Sandbox Code Playgroud)

非常重要的部分是最后关闭中的close()。

1.1.5。确保释放低级资源

为了确保正确释放系统资源,必须关闭与实体关联的内容流或响应本身

和:

1.1.6。消费实体内容

推荐使用实体内容的方法是使用其HttpEntity#getContent()或HttpEntity#writeTo(OutputStream)方法。HttpClient还带有EntityUtils类,该类公开了一些静态方法以更轻松地从实体中读取内容或信息。不必直接读取java.io.InputStream,而是可以使用此类的方法来检索字符串/字节数组中的整个内容主体。但是,强烈建议不要使用EntityUtils,除非响应实体源自受信任的HTTP服务器并且已知长度有限。

关于响应处理程序变体:

1.1.8。响应处理程序

处理响应的最简单,最方便的方法是使用ResponseHandler接口,该接口包括handleResponse(HttpResponse response)方法。这种方法完全使用户不必担心连接管理。

来自堆栈溢出的提示

您还可以阅读以下内容: 为什么作者使用EntityUtils.consume(httpEntity);?

边注

使用多线程连接管理器的要点是,您可以拥有一个(只有一个)客户端,并为整个应用程序共享它。您无需为每个请求构建一个客户端,也不必让它们共享一个连接管理器。虽然可以。
如果您使用缓存,Cookie,身份验证,那么拥有一个客户端可能会有所帮助。当为每个请求创建一个新客户端时,这将无法正常工作。

1.2.1。HttpClient线程安全

HttpClient实现应该是线程安全的。建议将此类的相同实例重用于多个请求执行。