本文介绍了如何使Spring Boot自动重新连接到PostgreSQL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行连接到PostgreSQL数据库的Spring Boot.我已经验证了如果在数据库之后启动Spring Boot,则数据已写入数据库.

I am running Spring Boot connecting to a PostgreSQL database. I have verified that data is written to the database if Spring Boot is started after the database.

spring.datasource.url = jdbc:postgresql://localhost/dbname
spring.datasource.username = user
spring.datasource.password = secret
spring.datasource.driver-class-name = org.postgresql.Driver
spring.datasource.testOnBorrow=true
spring.datasource.validationQuery=SELECT 1

当开发中的数据库发生更改时,我会遇到异常:PreparedStatementCallback; SQL []; This connection has been closed.; nested exception is org.postgresql.util.PSQLException: This connection has been closed.

When there are changes in the database in development, I run into exceptions:PreparedStatementCallback; SQL []; This connection has been closed.; nested exception is org.postgresql.util.PSQLException: This connection has been closed.

请注意,发生异常时,可以再次访问数据库;我认为问题在于连接是陈旧的,因为它最初连接的数据库端点由于重新启动而不再可用.重新启动Spring Boot可以解决该问题.

Note that the database is accessible again when the exceptions occur; I think the problem is that connection is stale because the database endpoint it originally connected to is no longer available because of the restart. Restarting Spring Boot resolves the issue.

如何配置Spring Boot使其重新连接到PostgreSQL,而无需重新启动它?

How do I configure Spring Boot to reconnect to PostgreSQL so that I do not need to restart it?

我试图按照 Spring Boot JPA中的答案-配置自动重新连接如何在连接时重新连接数据库jpa春季关闭?.我不确定PostgreSQL的行为是否与MySQL不同.我阅读了 Spring Boot文档没有帮助;我不了解所描述的组件,不足以理解我应该查看的文档.

I have attempted to follow the answers in Spring Boot JPA - configuring auto reconnect and How to reconnect database if the connection closed in spring jpa?. I am not sure whether the PostgreSQL behavior is different from MySQL. My reading of the Spring Boot documentation has not helped; I do not know the components described well enough to understand what documentation I should be looking at.

推荐答案

应该将Spring Boot配置为自动重新连接,问题是它不知道断开的连接.

Spring boot should be configured to reconnect automatically, problem is that it is not aware of the broken connection.

由于您已经在借用和验证查询中使用测试,因此只需尝试减少验证间隔,以便每次执行.

Since you are already using test on borrow and validation query, just try reducing validation interval so it is executed every time.

spring.datasource.tomcat.test-on-borrow=true
spring.datasource.tomcat.validation-query=SELECT 1
spring.datasource.tomcat.validation-interval=0

testOnBorrow上的

Tomcat jdbc连接池:

但是要注意validationInterval:

这篇关于如何使Spring Boot自动重新连接到PostgreSQL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 07:46