我正在運行Spring Boot連接到PostgreSQL數據庫。如果在數據庫之後啓動Spring Boot,我已驗證數據已寫入數據庫。如何讓Spring Boot自動重新連接到PostgreSQL?
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.
注意,數據庫訪問時,再次發生異常;我認爲問題在於連接已過時,因爲它最初連接到的數據庫端點由於重新啓動而不再可用。重新啓動Spring Boot可以解決問題。
如何配置Spring Boot重新連接到PostgreSQL,以便我不需要重新啓動它?
我試圖按照Spring Boot JPA - configuring auto reconnect和How to reconnect database if the connection closed in spring jpa?中的答案。我不確定PostgreSQL的行爲是否與MySQL不同。我對Spring Boot documentation的閱讀沒有幫助;我不知道所描述的組件是否足夠了解我應該查看哪些文檔。
您正在使用哪個連接池?如果你不使用它,你可能想嘗試切換到Hikari。在過去,我已經看到過這樣的問題,它使用'tomcat-jdbc',這是當前的默認連接池。 –
您有借用測試,但您可能還希望在空閒和空閒超時時設置檢查。這樣,連接被定期檢查並且如果無效則從池中移除。 –
@AndyWilkinson我想我使用的是tomcat-jdbc,因爲我的pom包含spring-boot-starter-jdbc。 – mattm