Apache HTTP客户端仅支持两个连接

5

我有以下代码,使用Apache HTTP客户端调用REST API方法。然而,仅可以使用上述客户端发送两个并行请求。是否有参数可设置最大连接数?

     HttpPost post = new HttpPost(resourcePath);
            addPayloadJsonString(payload, post);//set a String Entity
            setAuthHeader(post);// set Authorization: Basic header
            try {
                return httpClient.execute(post);

            } catch (IOException e) {
                String errorMsg = "Error while executing POST statement";
                log.error(errorMsg, e);


  throw new RestClientException(errorMsg, e);
        }

我正在使用的罐子如下:

org.apache.httpcomponents.httpclient_4.3.5.jar
org.apache.httpcomponents.httpcore_4.3.2.jar
1个回答

11

您可以使用HttpClientConnectionManager配置HttpClient。

请查看连接池管理器

ClientConnectionPoolManager维护一组HttpClientConnections,并能够为多个执行线程提供连接请求服务。连接基于路由进行池化。如果对已经存在于池中的路由发出请求,则将从池中租用连接,而不是创建全新的连接。

PoolingHttpClientConnectionManager在每个路由和总体上维护最大连接限制。默认情况下,此实现将每个给定路由创建不超过2个并发连接,并且总共不超过20个连接。对于许多实际应用程序来说,这些限制可能过于约束,特别是如果它们使用HTTP作为其服务的传输协议。

此示例展示了如何调整连接池参数:

PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
// Increase max total connection to 200
cm.setMaxTotal(200);
// Increase default max connection per route to 20
cm.setDefaultMaxPerRoute(20);
// Increase max connections for localhost:80 to 50
HttpHost localhost = new HttpHost("locahost", 80);
cm.setMaxPerRoute(new HttpRoute(localhost), 50);

CloseableHttpClient httpClient = HttpClients.custom()
        .setConnectionManager(cm)
        .build();

谢谢您的回答。只有一个问题。如果使用连接池管理器,当执行以下GET或POST时,我们不必关闭连接,对吗? HttpPost post = new HttpPost(resourcePath);
try { return httpClient.execute(post); } catch (IOException e) { //处理异常 }finally { post.releaseConnection(); }
- Udara S.S Liyanage

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接