【发布时间】:2023-08-16 09:25:02
【问题描述】:
我在生产环境中使用 apache httpclient 4.5 有一段时间了,但最近,随着新用例的添加,系统开始出现故障。
我们有多个通过 REST Web 服务进行通信的服务,客户端是 apache httpclient 4.5 的包装器。
假设我有服务 A 与服务 B 通信。通信正常工作,直到我重新启动服务 B。由于超时,我从服务 A 发起的下一次调用服务 B 失败。在做了一些研究之后,我发现出于性能原因(不再有 2 次握手等),底层 TCP 连接被重用。由于服务器已重新启动,因此底层 TCP 连接已过时。
阅读文档后,我发现我可以在 n 秒后使我的连接失效。假设我重新启动服务 B,那么调用将在前 n 秒内失败,但之后会重建连接。这是我实现的keepAliveStrategy
connManager = new PoolingHttpClientConnectionManager();
connManager.setMaxTotal(100);
connManager.setDefaultMaxPerRoute(10);
ConnectionKeepAliveStrategy keepAliveStrategy = new DefaultConnectionKeepAliveStrategy() {
public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
long keepAliveDuration = super.getKeepAliveDuration(response, context);
if (keepAliveDuration == -1) {
keepAliveDuration = 45 * 1000; // 45 seconds
}
return keepAliveDuration;
}
};
CloseableHttpClient closeableHttpClient = HttpClients.custom()
.setConnectionManager(connManager)
.setKeepAliveStrategy(keepAliveStrategy)
.build();
我只是想知道这是否是该库的正确用法。我是这样做的,还是我让一切都变得过于复杂?
【问题讨论】:
标签: java httpclient keep-alive