Apache HTTP 客户端只有两个连接是可能的

标签 apache rest http httpclient

我有以下代码使用 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);
        }

我正在使用的 jar 如下,

org.apache.httpcomponents.httpclient_4.3.5.jar
org.apache.httpcomponents.httpcore_4.3.2.jar

最佳答案

您可以使用 HttpClientConnectionManager 配置 HttpClient

看看Pooling connection manager .

ClientConnectionPoolManager maintains a pool of HttpClientConnections and is able to service connection requests from multiple execution threads. Connections are pooled on a per route basis. A request for a route which already the manager has persistent connections for available in the pool will be services by leasing a connection from the pool rather than creating a brand new connection.

PoolingHttpClientConnectionManager maintains a maximum limit of connections on a per route basis and in total. Per default this implementation will create no more than 2 concurrent connections per given route and no more 20 connections in total. For many real-world applications these limits may prove too constraining, especially if they use HTTP as a transport protocol for their services.

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

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();

关于Apache HTTP 客户端只有两个连接是可能的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26137818/

相关文章:

http - 使用 Squid 按需将文本附加到 HTTP 响应

apache - htaccess 与 MediaWiki htaccess 冲突

php - 启用 PHP Apache2

apache - 禁止访问,您无权访问此资源

java - 我可以使用多线程一次多次进行相同的休息调用吗?

Android WebView “tel:” & "mailto:"链接显示未找到网页

php - 如何在我的 PHP-Apache-PostgreSQL 站点中嵌入 python 脚本?

java - 如何将参数从prototypejs客户端传递到rest web服务

java - 在 CXF 中使用 log4j 登录和注销拦截器消息

security - 如果我可以使用 https,为什么还要使用相关协议(protocol)?