gpt4 book ai didi

java - 为什么 PoolingHttpClientConnectionManager 提供越来越慢的连接?

转载 作者:搜寻专家 更新时间:2023-10-30 23:02:57 24 4
gpt4 key购买 nike

我正在使用 httpClient 4.3.6CloseableHttpClientPoolingHttpClientConnectionManager 提供服务。

我当前的设置包括 200 个线程,它们通过客户端并发执行 GET 请求。我试图最大化线程每秒可以处理的请求数,但是一旦我开始执行超过 ~100/s,httpClient.execute() 请求就开始占用越来越多的请求是时候回来了。我确实知道为请求提供服务的机器并没有变慢,问题的根源在于 httpClient 库或我机器上的资源。

这是我的客户端实例

    // Start up an eviction thread.
// remove idle (for 50ms) connections every 50 ms
IdleConnectionMonitorThread monitor = new IdleConnectionMonitorThread(cm);
// Don't stop quitting.
monitor.setDaemon(true);
monitor.start();

PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
// increase connection limit
cm.setMaxTotal(2000);
cm.setDefaultMaxPerRoute(2000);
// create client
HttpClientBuilder builder = HttpClientBuilder.create();
builder.setDefaultRequestConfig(RequestConfig.custom().build());
builder.setConnectionManager(cm);
this.httpClient = builder.build();

execute 方法的平均执行时间在我开始线程执行时稳步但缓慢地增加,并且在请求率下降时迅速下降。

    HttpGet getRequest = new HttpGet(uri);
HttpClientContext context = HttpClientContext.create();

try(CloseableHttpResponse response = httpClient.execute(getRequest, context);) {

int returnStatus = response.getStatusLine().getStatusCode();

switch (returnStatus){
case 404:
// deal with 404
case 200:
HttpEntity entity = response.getEntity();

if (entity != null) {
entity = new BufferedHttpEntity(entity);
InputStream instream = entity.getContent();
try{
// deal with instream
} finally {
instream.close();
// make sure everything is consumed
EntityUtils.consume(entity);
}
} else {
// throw exception
}
default:
// weird codes
}
}

最佳答案

我不确定拥有这么多并发连接是否有意义。你有多少个核心?也许您应该使用异步 http 客户端来防止线程争夺资源。

关于java - 为什么 PoolingHttpClientConnectionManager 提供越来越慢的连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29155352/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com