最近在部署Spring Boot應用服務時,碰到 JPA鏈接Mysql過一段時間會中斷的問題。
多方查證才知道:在Spring Boot JPA鏈接Mysql的過程當中,通過 8小時後會發現斷連的狀況(即mysql在默認的狀況下,若是發現一個鏈接空閒時間超過8小時,將會在數據庫端自動關閉這個鏈接。mysql wait_timeout 爲8小時)。mysql
application.properties 中數據庫 配置文件以下:spring
spring.datasource.url=jdbc:mysql://localhost/test spring.datasource.username=username spring.datasource.password=password spring.datasource.driver-class-name=com.mysql.jdbc.Driver
解決方法以下:sql
spring.datasource.url=jdbc:mysql://localhost/test?autoReconnect=true
spring.datasource.test-on-borrow=false #(即在獲取Connection對象時檢測其可用性),不過這樣會影響性能,可是這個配置是最有效的。 spring.datasource.test-while-idle=true spring.datasource.time-between-eviction-runs-millis=3600000
set global interactive_timeout=28800; set global wait_timeout=28800; show global variables like 'wait_timeout';