【问题标题】:Apache HttpComponents BasicHttpClientConnectionManagerApache HttpComponents BasicHttpClientConnectionManager
【发布时间】:2016-08-25 08:09:01
【问题描述】:

我最近从java.net 切换到org.apache.http.client,我设置了ClosableHttpClient 和HttpClientBuilder。作为连接管理器,我使用的是BasicHttpClientConnectionManager。

现在我遇到的问题是,当我创建一些 HTTP 请求时,我经常遇到超时异常。似乎连接管理器保持连接打开以重用它们,但如果系统空闲几分钟,则此连接将超时,当我发出下一个请求时,我得到的第一件事就是超时。再重复一次相同的请求,通常不会有任何问题。

有没有办法配置BasicHttpClientConnectionManager 以便不重复使用其连接并每次都创建一个新连接?

【问题讨论】:

  • @ScaryWombat 查看 java.net.Socket 的文档,似乎套接字超时只会控制 read() 调用将阻塞多长时间。你确定那适合我的情况吗? closeIdleConnections 似乎只会关闭 当前 空闲连接,并且只会产生一次效果。但我需要一些我可以配置一次的东西,它将适用于所有打开的连接。
  • 对不起,你是对的
  • @ScaryWombat 好的,谢谢,您还有其他建议吗?

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


【解决方案1】:

有几种方法可以解决这个问题

  1. 一旦不再需要,就驱逐空闲连接。下面的代码通过在每次 HTTP 交换后关闭持久连接来有效地禁用连接持久性。

    BasicHttpClientConnectionManager cm = new BasicHttpClientConnectionManager();
    CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(cm).build();
    ...
    try (CloseableHttpResponse response = httpclient.execute(new HttpGet("/"))) {
        System.out.println(response.getStatusLine());
        EntityUtils.consume(response.getEntity());
    }
    cm.closeIdleConnections(0, TimeUnit.MILLISECONDS);
    
  2. 将连接保持活动时间限制为相对较小的东西

    BasicHttpClientConnectionManager cm = new BasicHttpClientConnectionManager();
    CloseableHttpClient httpclient = HttpClients.custom()
            .setConnectionManager(cm)
            .setKeepAliveStrategy((response, context) -> 1000)
            .build();
    try (CloseableHttpResponse response = httpclient.execute(new HttpGet("/"))) {
        System.out.println(response.getStatusLine());
        EntityUtils.consume(response.getEntity());
    }
    
  3. (推荐)使用池连接管理器并将连接总生存时间设置为有限值。与池化连接管理器相比,使用基本连接管理器没有任何好处,除非您的代码需要在 EJB 容器中运行。

    CloseableHttpClient httpclient = HttpClients.custom()
            .setConnectionTimeToLive(5, TimeUnit.SECONDS)
            .build();
    try (CloseableHttpResponse response = httpclient.execute(new HttpGet("/"))) {
        System.out.println(response.getStatusLine());
        EntityUtils.consume(response.getEntity());
    }
    

【讨论】:

    猜你喜欢
    • 2011-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-27
    • 2013-05-23
    相关资源
    最近更新 更多