CloseableHttpClient 在高并发下每几分钟阻塞一次

CloseableHttpClient blocks per few minutes under high concurrency

我正在使用 httpcomponents 做 http 请求。我已经将connectionRequestTimeoutconnectTimeoutsocketTimeout设置为相同的时间(比如8000ms)。系统处于高并发状态,大部分时间性能良好,但某些请求耗时数秒,与每分钟超时(~8000ms)相同。这是代码片段:

    RequestConfig config = RequestConfig.custom().setConnectionRequestTimeout(TIMEOUT).setConnectTimeout(TIMEOUT).setSocketTimeout(TIMEOUT).build();
    CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
    HttpUriRequest request = null;
    switch (method) {
        case GET:
            String getUrl = url;
            if (null != paramData) {
                getUrl += "?" + paramData;
            }
            request = new HttpGet(getUrl);
            break;
        case POST:
            ...
        default:
            ...
    }
    CloseableHttpResponse response = null;
    try {
        long start = System.currentTimeMillis();
        response = client.execute(request);
        long time = System.currentTimeMillis() - start;
        // ***************************
        // Sometime the log shows the cost is a few milliseconds more than TIMEOUT,
        // but it does not throw any timeout exception and the response is fine.
        // ***************************
        LOG.debug("cost {}ms", time);
        int resultCode = response.getStatusLine().getStatusCode();
        HttpEntity entity = response.getEntity();
        String resultJson = EntityUtils.toString(entity, UTF_8);
        if (HttpStatus.SC_OK == resultCode) {
            ...
        }
    } catch (Exception e) {
        ...
    } finally {
        //abort the request
        if (null != request && !request.isAborted()) {
            request.abort();
        }
        //close the connection
        HttpClientUtils.closeQuietly(client);
        HttpClientUtils.closeQuietly(response);
    }

httpcomponents的版本是4.5.2,jdk是openjdk1.8.0_92。 此外,我应该使用 CloseableHttpClient 作为单例以获得更好的性能吗?

CloseableHttpClient 应该使用单例以获得更好的性能。 您还可以根据需要在 HttpClientBuilder.

中定义连接数

此外,socketTimeout 应该大于 connectionTimeOut,这将提供更多时间来读取套接字。