[转]reactor.netty.http.client.PrematureCloseException: Connection prematurely closed BEFORE response

一、背景
可能大家在使用Spring Cloud Gateway构建微服务网关的时候,过五关斩六将,Reactor没能难倒我们,链路追踪没能难倒我们,最后在上线之后发现许多奇妙的问题,这些奇妙的问题还无从下手,比如这个堆栈,深入使用过SCG的人一定不会陌生:

reactor.netty.http.client.PrematureCloseException: Connection prematurely closed BEFORE response
Suppressed: reactor.core.publisher.FluxOnAssembly$OnAssemblyException:

类似的还有:
Connection prematurely closed DURING response 。。。等等

百度了一圈,鲜有人提供解决方案,有条件的Google了一把,跟着官方调整几个参数,有用没用也不得而知,最后反正就不了了之。

云服务器厂商提供的环境中,不同服务之间的网络请求会先经过防火墙,防火墙会杀掉空闲过久的连接,没有通知调用的双方,导致请求发起者再使用该连接时,发送的数据会被防火墙直接丢弃。
Tomcat默认keepAliveTimeout为20s,如果刚好在Tomcat关闭连接的途中,发起方使用该连接写数据,则会提示请求已关闭的错误,具体异常为:reactor.netty.http.client.PrematureCloseException

解决方案

官方 github 已经给出了解决方式 :reactor.netty.http.client.PrematureCloseException: Connection prematurely closed BEFORE response,springboot2.1.6 · Issue #1148 · spring-cloud/spring-cloud-gateway · GitHub

@Ziemowit Thank you very mutch. It solved my problem.
The Spring Cloud Gateway project spring.cloud.gateway.httpclient.pool.max-idle-time defalut value was null (there is no max).
my proxy target server was tomcat, server.connection-timeout default was 20000ms.
My server was set to 100ms, 100ms was to short, it cause many PrematureCloseException.

My solution:

server.connection-timeout=5000
spring.cloud.gateway.httpclient.pool.max-idle-time=2000ms


Notice: spring.cloud.gateway.httpclient.pool.max-idle-time must be less than or server.connection-timeout

 

可以改变Netty从连接池取连接的策略为后进先出:-D reactor.netty.pool.leasingStrategy=lifo,并修改连接的最大空闲时间,让其小于下游Tomcat的keepAliveTimeout:spring.cloud.gateway.httpclient.pool.maxIdleTime=10000
tomcat还有个参数配置一个连接最大处理请求的个数,超过这个值也会断开连接,默认是100,可以通过设置server.tomcat.maxKeepAliveRequests=-1来不限制请求个数。

来源地址:

https://blog.51cto.com/u_6346066/3282076icon-default.png?t=N7T8https://blog.51cto.com/u_6346066/3282076https://blog.csdn.net/liuzhenghua66/article/details/132312929icon-default.png?t=N7T8https://blog.csdn.net/liuzhenghua66/article/details/132312929

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值