什么会导致 Spring 使用 RestTemplate 启动 Rest Api 时连接失效

What can cause stale connection in Spring boot Restapi using RestTemplate

我读到“过时的连接是服务器断开连接但客户端不知道的结果。”但是我正在尝试寻找如果我使用基于 SpringBoot RestTemplate 的应用程序(进一步使用 Apache 的 PoolConnectionManager)并从我的应用程序调用另一个 API 的情况下如何可能?在这种情况下,我的应用程序是客户端,我调用的应用程序充当服务器。如果我点击那个应用程序,并且我正在调用的 api 收到请求但在完全填充请求之前不知何故崩溃了。在这种情况下,我肯定会得到例外。而且我很确定万一 ​​PoolConnectionManager 必须关闭该连接。那我怎么会有过时的连接?

默认情况下,PoolConnectionManager 不会关闭失效的连接,除非您将其配置为执行此操作。方法 setValidateAfterInactivity() 用于配置该时间段。

PoolingHttpClientConnectionManager connManager 
          = new PoolingHttpClientConnectionManager();
        connManager.setValidateAfterInactivity(20);

        HttpClient httpClient = HttpClients.custom().setConnectionManager(connManager).build();

您可以在 Whosebug 中找到类似的示例 here

** 跟进问题后更新**

根据文档,4.4 版的行为有所改变。

The handling of stale connections was changed in version 4.4. Previously, the code would check every connection by default before re-using it. The code now only checks the connection if the elapsed time since the last use of the connection exceeds the timeout that has been set. The default timeout is set to 2000ms

https://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/impl/conn/PoolingHttpClientConnectionManager.html#setValidateAfterInactivity(int)