解决Springboot运行时Postgrasql报错:ERROR SqlExceptionHelper:146 - This connection has been closed.

时间:2025-02-09 17:27:25
Springboot运行时,MQ突然报错:
stderr: : could not inspect JDBC autocommit mode; nested exception is : could not inspect JDBC autocommit mode
stderr: 	at $(:122)
stderr: 	at (:179)
stderr: 	at (:81)
stderr: 	at (:325)
stderr: 	at (:103)
stderr: 	at (:573)
stderr: 	at .$(Unknown Source)
stderr: 	at $(:415)
stderr: 	at (:136)
stderr: 	at .jdbc2.(:680)
stderr: 	at (:108)
stderr: 	at (:322)
stdout: 00:00:00,002 ERROR SqlExceptionHelper:146 - This connection has been closed.
stderr: 	at (:221)
stderr: 	at $(:122)
stderr: 	at (:92)
stderr: 	at .(Unknown Source)
stderr: 	at $(:293)
stderr: 	at (:325)
stderr: 	at (:573)
stderr: 	at $(:362)
stderr: 	at (:179)
stderr: 	at (:81)
stderr: 	at (:322)
stderr: 	at (:417)
stderr: 	at (:92)
stderr: 	at (:179)
stderr: 	at .$(Unknown Source)
stderr: 	at (:497)
stderr: 	at $(:511)
stderr: 	at $(:617)
stderr: 	at (:199)
stderr: 	at (:67)
stderr: 	at $(:110)
stderr: 	at (:74)
stderr: 	at (:179)
stderr: 	at .(Unknown Source)
stderr: 	at (:497)
stderr: 	... 48 more

细眼一看,关键词是

connection has been closed

报错一直在定时任务运行时出现,调用数据库的时候,猜想是Pg数据库断了,询问运维查看数据库运行情况,回答是重启过,目前运行正常。

再次猜测是数据库重启导致服务连接异常,且并未重启连接,查阅BAIDU,获取的内容主要是以下2篇

/doc/9437385695723670x776/postgres-connection-has-been-closed-error-in-spring-boot

/questions/31881250/heroku-postgres-this-connection-has-been-closed


发现Springboot并未做断接重连的配置。

1.先做对服务错误发生的验证,本地启动应用,在定时服务正常运行时,对pg数据库进行重启,果然,错误重现了。

2.于是对配置进行修改,增加一下内容:

#是否在自动回收超时连接的时候打印连接的超时错误
-abandoned=true
#是否自动回收超时连接
-abandoned=true
#超时时间(以秒数为单位)
-abandoned-timeout=180
##<!-- 超时等待时间以毫秒为单位 6000毫秒/1000等于60秒 -->
-wait=1000
-while-idle=true
#检测数据库的查询语句
-query=select 1
-on-borrow=true
#每隔五分钟检测空闲超过10分钟的连接
-evictable-idle-time-millis=600000
-between-eviction-runs-millis=300000


3.再次在本地进行测试,启动定时服务,把数据库进行重启,结果是,在数据库关闭时,错误出现了,但是提示为

No server chosen by ReadPreferenceServerSelector{readPreference=primary} from cluster description ClusterDescription
{type=STANDALONE, connectionMode=MULTIPLE, all=[ServerDescription{address=10.2.130.179:8888, type=UNKNOWN, state=CONNECTING, exception=
{: Exception opening socket}, caused by {: Connection refused}}]}. Waiting for 30000 ms before timing out

在数据库恢复之后,代码恢复正常运行。问题解决


引用配置地址:

/mr_phy/article/details/73323992