PoolingHttpClientConnectionManager

时间:2018-09-13 20:00:44

标签: java apache-httpclient-4.x

我已经用以下方法配置了PoolingHttpClientConnectionManager:

Total Max Connections: 100
Default Max Per Route: 10

我在运行时得到这些统计信息(通常,空闲,活动和待处理的总和超出了限制):

Idle: 15 - Active: 0 - Pending: 0 - Maximum: 100

这意味着连接器未遵循最大每条路由的值。我知道在这种情况下这没什么大不了的,但是随着数据量的增加,这可能是一个问题。有人看到过这种行为吗?

这是检索统计信息的代码:

int available = connMan.getTotalStats().getAvailable();
int active = connMan.getTotalStats().getLeased();
int pending = connMan.getTotalStats().getPending();
int maximum = connMan.getTotalStats().getMax();

这是连接管理器配置:

connManager = new PoolingHttpClientConnectionManager();
connManager.setMaxTotal(100);
connManager.setDefaultMaxPerRoute(10);

这是CloseableHttpClient的创建:

RequestConfig config = RequestConfig.custom()
.setSocketTimeout(sourceInfo.getSocketTimeout())
.setConnectTimeout(sourceInfo.getConnectTimeout())
.setConnectionRequestTimeout(sourceInfo.getConnectionRequestTimeout())
.setTargetPreferredAuthSchemes(sourceInfo.getAuthSchemes())
.build();

HttpClientBuilder clientBuilder = HttpClients.custom()
.setDefaultRequestConfig(config);

clientBuilder.setConnectionManager(connManager);

该应用程序是多线程的,但是它们都使用相同的客户端。有一个客户端上下文:

this.context = HttpClientContext.create();
this.context.setCredentialsProvider(info.getCredentialsProvider());

但是,鉴于文档指出线程之间不可共享上下文,因此会在每个请求上将其克隆:

HttpClientContext baseContext = getHttpClientContext();
context = HttpClientContext.create();
context.setCredentialsProvider(baseContext.getCredentialsProvider());
context.setAuthCache(baseContext.getAuthCache());
context.setCookieStore(baseContext.getCookieStore());
context.setUserToken(baseContext.getUserToken(Principal.class));

String responseBody = conn.execute(request, responseHandler, context);

这是响应处理程序:

public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
          try {
            int status = response.getStatusLine().getStatusCode();
            HttpEntity entity = response.getEntity();
            if (status >= 200 && status < 300) {          
              String responseEntity = entity != null ? EntityUtils.toString(entity) : null;
              EntityUtils.consume(entity);
              return responseEntity;
            } else {
              if (entity != null) {
                String responseBody = EntityUtils.toString(entity);
                EntityUtils.consumeQuietly(entity);
                throw new ClientProtocolException(String.format("Unexpected response status: %d - %s \n %s", status, response.getStatusLine().getReasonPhrase(), responseBody));
              } else {
                EntityUtils.consumeQuietly(entity);
                throw new ClientProtocolException(String.format("Unexpected response status: %d - %s", status, response.getStatusLine().getReasonPhrase()));
              }
            }
          } catch(Exception ex) {
            throw ex;
          }
        }

0 个答案:

没有答案