HttpClient 4.x挂起socketRead(本机方法)

时间:2016-05-26 17:46:51

标签: java sockets httpclient apache-httpclient-4.x apache-httpcomponents

我使用HttpClient- 4.3.4调用远程REST服务。客户端挂起此行,最后抛出ReadTimeOut异常。

at java.net.SocketInputStream.socketRead#(Native Method)

请求量一天几乎是数百万,我得到了ReadTimeOut错误的1%。它间歇性地发生。我已将超时设置为6秒,这就是我获得超时异常的原因,否则我认为它会挂起更长时间。我也启用了StaleConnectionCheck。我查看了服务提供商的响应时间,服务在100毫秒内响应。

public MyRespBean doGet(
      String host, String path, List<NameValuePair> nameValuePairs, Map<String, String> headers)
      throws URISyntaxException, IOException {

      CloseableHttpClient httpClient = getHttpClient();
      URI uri = buildUri(host, path, nameValuePairs);
      HttpGet httpGet = new HttpGet(uri);
      httpGet.setHeader("Connection", "close");
      addHeaders(httpGet, headers, authParams);
      MyRespBean respBean = httpClient.execute(httpGet, new SimpleResponseHandler());
      httpClient.close();
      return respBean;
  }



public CloseableHttpClient getHttpClient() {
   CloseableHttpClient httpClient = null;
   RequestConfig requestConfig = null;
   if (StringUtils.isNotBlank(proxyHost) && proxyPort != null && StringUtils
       .isNotBlank(proxyScheme)) {
       HttpHost proxy = new HttpHost(proxyHost, proxyPort, proxyScheme);
       requestConfig = RequestConfig.custom().setSocketTimeout(6000).setConnectTimeout(6000)
                      .setStaleConnectionCheckEnabled(true).setProxy(proxy)
                      .build();

   } else {
       requestConfig = RequestConfig.custom().setSocketTimeout(6000).setConnectTimeout(6000)
                      .setStaleConnectionCheckEnabled(true).build();
   }
   httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();
   return httpClient;
}

Maven依赖

   `enter code here`<dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpcore</artifactId>
        <version>4.3.2</version>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.3.4</version>
        <scope>compile</scope>
    </dependency>

我看了一些其他建议的帖子 -

  1. 设置超时(这实际上不是解决方案,无论如何我都设置了它)
  2. 服务提供商可能需要更长时间 - (不在我的情况下)
  3. 可能存在StaleConnection - (我已经检查过了)
  4. 可能导致此类问题的原因是什么?

0 个答案:

没有答案