高并发下每几分钟CloseableHttpClient块

时间:2017-05-02 04:50:36

标签: apache-httpcomponents

我使用httpcomponents来做http请求。我已将connectionRequestTimeoutconnectTimeoutsocketTimeout设置为同一时间(例如8000毫秒)。系统具有高并发性,大部分时间表现良好,但有些请求的成本为秒,与每分钟的超时(~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的版本是openjdk 1.8.0_92。 此外,我应该使用CloseableHttpClient作为单身人员以获得更好的表现吗?

1 个答案:

答案 0 :(得分:1)

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

socketTimeout也应该更多是connectionTimeOut,这将有更多时间来读取套接字。