1.现象:业务反馈接口返回Internal Server Error
经排查sringcloudgateway中有这个日志报错:
18:49:40.317 [reactor-http-epoll-4] ERROR org.springframework.core.log.CompositeLog.error(CompositeLog.java:102) [traceId: ] - [009a73dc-74671082] 500 Server Error for HTTP POST "某接口url"
reactor.netty.http.client.PrematureCloseException: Connection prematurely closed BEFORE response
Suppressed: reactor.core.publisher.FluxOnAssembly$OnAssemblyException:
Error has been observed at the following site(s):
*__checkpoint ⇢ org.springframework.cloud.gateway.filter.WeightCalculatorWebFilter [DefaultWebFilterChain]
*__checkpoint ⇢ com.alibaba.csp.sentinel.adapter.spring.webflux.SentinelWebFluxFilter [DefaultWebFilterChain]
*__checkpoint ⇢ org.springframework.boot.actuate.metrics.web.reactive.server.MetricsWebFilter [DefaultWebFilterChain]
*__checkpoint ⇢ HTTP POST "/marketing-activity-task/api/open/v1/task/taskMatchQuery" [ExceptionHandlingWebHandler]
Original Stack Trace:
reactor.netty.http.client.PrematureCloseException: Connection prematurely closed BEFORE response
代表该请求在请求途中被打断,抛出异常。
参考帖子:https://blog.csdn.net/rickiyeat/article/details/107900585
2.解决方案:调整启动参数+连接时间
1.在AGD opengateway服务的启动脚本中加上-Dreactor.netty.pool.leasingStrategy=lifo
2.opengateway新增nacos配置:spring.cloud.gateway.httpclient.pool.maxIdleTime
先检查common的nacos配置中restTemplate.config.connection.connectTimeout
该配置为建立连接成功后,从服务器读取超时,单位毫秒ms
修改点:spring.cloud.gateway.httpclient.pool.maxIdleTime<restTemplate.config.connection.connectTimeout
设置空闲请求时间小于连接后端服务的超时时间,这样能够确保SCG回收请求在后端服务回收请求之前,也就可以避免拿到旧连接刚好在请求途中被强行close掉。
3.配置含义
-Dreactor.netty.pool.leasingStrategy=lifo
-Dreactor.netty.pool.leasingStrategy=lifo是一个用于配置 Reactor Netty 连接池租赁策略的 JVM 启动参数。
具体含义:
reactor.netty.pool.leasingStrategy用于指定连接池中连接的租赁(leasing)策略。
lifo表示采用后进先出(Last In, First Out)策略来分配连接。
在 LIFO 策略下,连接池中最新归还的连接会被优先再次分配使用。
为什么使用 LIFO:
LIFO 策略通常可以提高连接的重用效率,因为最新归还的连接更可能处于活跃状态,减少连接被关闭或失效的风险。
有助于提升性能和资源利用率。
总结:-Dreactor.netty.pool.leasingStrategy=lifo配置 Reactor Netty 连接池使用后进先出策略来租赁连接,从而优化连接的重用和性能。
spring.cloud.gateway.httpclient.pool.maxIdleTime
spring.cloud.gateway.httpclient.pool.maxIdleTime 这个配置项用于配置 Spring Cloud Gateway 中底层使用的 HttpClient 连接池中,连接的最大空闲时间。
具体含义是:
maxIdleTime表示连接在连接池中允许保持空闲状态的最长时间。
如果一个连接在连接池中空闲时间超过了这个配置的时间,连接将被关闭并从连接池中移除。
这样可以避免连接长时间空闲导致资源浪费或连接失效。
通常,这个时间单位是毫秒(具体单位需要根据版本文档确认),配置合理的 maxIdleTime 可以帮助提升连接池的资源利用效率和系统的稳定性。
总结:spring.cloud.gateway.httpclient.pool.maxIdleTime用来控制 HttpClient 连接池中连接的最大空闲时间,超过该时间的空闲连接会被关闭释放。
restTemplate.config.connection.connectTimeout
restTemplate.config.connection.connectTimeout 这个配置项用于设置 RestTemplate 发起 HTTP 请求时,建立与服务器的连接超时时间。
具体含义是:
connectTimeout表示客户端尝试与服务器建立 TCP 连接时,等待连接成功的最大时间。
如果在这个时间内连接没有建立成功,连接尝试会被中断,抛出连接超时异常。
该超时时间通常以毫秒为单位。
作用:
防止客户端因为服务器无响应或网络问题而长时间阻塞在连接建立阶段。
提升系统的响应速度和稳定性。
总结:restTemplate.config.connection.connectTimeout用来配置 RestTemplate 连接服务器时的超时时间,超过该时间未连接成功则会报超时错误。