2017-05-02 9 views
0

http 요청을 처리하기 위해 httpcomponents를 사용하고 있습니다. connectionRequestTimeout, connectTimeoutsocketTimeout을 같은 시간 (예 : 8000ms)으로 설정했습니다. 시스템은 동시성이 높으며 성능이 좋은 대부분의 시간이지만 일부 요청은 분당 시간 초과 (~ 8000ms)와 동일합니다.높은 동시성에서 몇 분당 CloseableHttpClient 블록

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는 1.8.0_92 오픈 JDK입니다 : 여기에 코드입니다. 더 나은 성능을 위해 CloseableHttpClient을 싱글 톤으로 사용해야합니까?

+0

이 문제는 'CloseableHttpClient'를 싱글 톤으로 설정하여 해결되었습니다. 나는 모든 http 요청에 대해 클라이언트를'new'하는 것은 매우 비싸다고 생각한다. BTW, 우리는 클라이언트를 재사용하고 싶다면'CloseableHttpClient'를'close '해서는 안됩니다. –

+0

아래 답변을 수락 해주십시오. 그것은 다른 사람들이 비슷한 문제를 푸는데 도움이 될 것입니다. 감사 –

답변

1

CloseableHttpClient은 성능 향상을 위해 싱글 톤을 사용해야합니다. 요구 사항에 따라 연결 수를 HttpClientBuilder에 정의 할 수도 있습니다.

또한 socketTimeout이 connectionTimeOut 이상이어야합니다. 그러면 소켓을 읽을 시간이 더 늘어납니다.