问题描述
我有以下代码来使用Apache HTTP客户端调用REST API方法。但是,只能使用上述客户端发送两个并行请求。
是否有设置max-connections的参数?
I have below code to invoke a REST API method using Apache HTTP client. However only two parallel requests could be sent using above client.Is there any parameter to set max-connections?
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
推荐答案
您可以使用
You can configure the HttpClient with HttpClientConnectionManager
看看。
PoolingHttpClientConnectionManager
维持每个路由和总计的最大连接数限制。默认情况下,此实现将为每个给定路由创建不超过2个并发连接,并且总共不再有20个连接。对于许多实际应用程序,这些限制可能过于严格,特别是如果他们使用HTTP作为其服务的传输协议。
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.
示例显示了如何调整连接池参数:
This example shows how the connection pool parameters can be adjusted:
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客户端只能有两个连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!