现象:
我在Java代码中使用org.springframework.web.reactive.function.client.WebClient
进行网络请求,一开始会有比较多的偶发报错:Connection prematurely closed BEFORE response,网络连接莫名其妙就断了。
处理:
在网上找了挺多资料,就感觉https://stackoverflow.com/questions/78354966/reactor-netty-connection-prematurely-closed-before-response-with-webclient和它的回答中提到的https://projectreactor.io/docs/netty/release/reference/index.html#connection-pool-timeout起到了些作用:把maxIdleTime设置到一个比较低的值。maxIdleTime表示连接在连接池中保持空闲状态的最大时间。
When you configure maxIdleTime, you should consider the idle timeout configuration on the target server. Choose a configuration that is equal to or less than the one on the target server. By doing so, you can reduce the I/O issues caused by a connection closed by the target server.
我大致的理解是,maxIdleTime只是client端的连接池配置,它管不到复杂的网络中间结点和目标服务器可能的超时配置,如果不把它设小一点,可能中间环节或者目标服务器把连接断掉了,但是client并没感知到而是继续使用实际已经失效的连接,而导致出错。而当我们把它设小一点,就可以回避这个问题。
所以我做了如下改动:
后面观察到报错确实少了很多,但是依然会少数出现。只能说把maxIdleTime设置到一个较小值是有效的,但是还要看看是否有彻底解决的办法。
待研究办法:evictInBackground
Errorhandling with Spring Webclient and Reactor
stackoverflow:Project Reactor - ConnectionProvider.evictInBackground()