【问题标题】:CloseableHttpClient blocks per few minutes under high concurrencyCloseableHttpClient 高并发下每分钟阻塞一次
【发布时间】:2017-05-02 04:50:35
【问题描述】:

我正在使用 httpcomponents 来执行 http 请求。我已将connectionRequestTimeoutconnectTimeoutsocketTimeout 设置为同一时间(例如8000ms)。系统处于高并发状态,大部分时间运行良好,但有些请求花费秒数,与每分钟超时时间(~8000ms)相同。这是代码sn-p:

    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是openjdk 1.8.0_92。 此外,我应该使用CloseableHttpClient 作为单例以获得更好的性能吗?

【问题讨论】:

  • 这个问题已经通过将CloseableHttpClient 设置为单例来解决。我认为new 一个客户端对于每个 http 请求都是非常昂贵的。顺便说一句,如果我们想重用客户端,我们不应该 close CloseableHttpClient
  • 您能接受下面的答案吗?它将帮助其他人解决他们的类似问题。谢谢

标签: apache-httpcomponents


【解决方案1】:

CloseableHttpClient 应该使用单例以获得更好的性能。 您也可以在HttpClientBuilder中根据您的要求定义连接数。

socketTimeout 也应该比 connectionTimeOut 多,这样可以有更多的时间来读取套接字。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-15
    • 1970-01-01
    • 1970-01-01
    • 2015-03-31
    相关资源
    最近更新 更多