我最近从 java.net
切换过来至org.apache.http.client
,我设置了一个 ClosableHttpClient
与 HttpClientBuilder
。作为连接管理器,我使用 BasicHttpClientConnectionManager
.
现在我遇到一个问题,当我创建一些 HTTP 请求时,我经常遇到超时异常。连接管理器似乎保持连接打开以重用它们,但如果系统空闲几分钟,那么此连接将超时,当我发出下一个请求时,我得到的第一件事就是超时。再次重复相同的请求通常不会出现任何问题。
有没有办法配置 BasicHttpClientConnectionManager
为了不重用其连接并每次创建一个新连接?
最佳答案
有几种方法可以解决这个问题
删除不再需要的空闲连接。下面的代码通过在每次 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);
将连接保持 Activity 时间限制为相对较小的时间
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()); }
(推荐) 使用池连接管理器并将连接总生存时间设置为有限值。与池连接管理器相比,使用基本连接管理器没有任何好处,除非您的代码预计在 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()); }
关于java - Apache HttpComponents BasicHttpClientConnectionManager,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39139902/