【问题标题】:Apache http client Read Timed OutApache http 客户端读取超时
【发布时间】:2016-01-05 18:40:06
【问题描述】:

我正在使用 apache http client api 4.5 来访问服务器。当服务器负载过重时,我收到错误

“[读取] I/O 错误:读取超时”

这是我的配置

private CookieStore cookieStore = new BasicCookieStore();
private CloseableHttpClient httpClient;

private final String USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36";
private HttpClientContext httpContext = new HttpClientContext();
private RequestConfig requestConfig = RequestConfig.custom()
        .setSocketTimeout(5000).
        setConnectTimeout(10000).build();

private PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();

public MyHttpClient() {

    cm.setMaxTotal(50);
    cm.setDefaultMaxPerRoute(10);

    HttpHost host = new HttpHost("localhost", 80);
    cm.setMaxPerRoute(new HttpRoute(host), 5);


    DefaultServiceUnavailableRetryStrategy retryStrategy = new DefaultServiceUnavailableRetryStrategy(5, 1);


    SocketConfig socketConfig = SocketConfig.custom()
            .setSoKeepAlive(true)
            .setSoReuseAddress(true)
            .setTcpNoDelay(true)
            .setSoTimeout(10000).build();

    httpContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);
    HttpClientBuilder builder= HttpClients.custom();

    builder.setMaxConnPerRoute(50)
        .setConnectionManager(cm)
        .setConnectionTimeToLive(10000, TimeUnit.MILLISECONDS)
        .setDefaultCookieStore(cookieStore)
        .setRedirectStrategy(new LaxRedirectStrategy())
        .setDefaultSocketConfig(socketConfig)
        .setServiceUnavailableRetryStrategy(retryStrategy)
        .setKeepAliveStrategy(keepAliveStrategy)
        .setRetryHandler(myRetryHandler);


    httpClient=builder.build();
}

我了解问题的原因

读取超时是等待读取数据的超时时间

但我想知道

  1. 如果有任何方法/配置可以避免读取超时错误
  2. 什么可能是最佳设置,以便我的客户端在服务器负载不足时不会失败。

我在这里看到了类似的帖子,但没有回复 Similar issue

【问题讨论】:

  • 补充说明:微软技术中存在类似的软件,在负载下也表现良好。 .net/ms 技术是否有额外的功能使它们变得健壮
  • 你找到解决办法了吗?

标签: apache-httpclient-4.x


【解决方案1】:

我认为错误消息与上面的响应无关。注意时间偏移。如果它是该响应的一部分,它将具有与该响应行相同的时间戳。这只是发生超时并被记录的时间点。

【讨论】:

    【解决方案2】:

    出现此类错误的原因之一可能是服务器在响应后关闭了 HTTP 连接。如果是这种情况,则可以通过禁用客户端的连接重用来避免此错误,因此客户端无需验证连接是否仍然存在:

    builder.setConnectionReuseStrategy( (response, context) -> false );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-03
      • 1970-01-01
      • 2014-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-28
      • 2014-05-16
      相关资源
      最近更新 更多