【发布时间】:2015-03-19 21:29:18
【问题描述】:
我正在使用 httpClient 4.3.6,CloseableHttpClient 由 PoolingHttpClientConnectionManager 提供服务。
我当前的设置包括 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
}
}
【问题讨论】:
标签: java http httpclient apache-httpclient-4.x