在Spring Boot JPA連接Mysql的過(guò)程中,經(jīng)過(guò) 8小時(shí)后會(huì)發(fā)現(xiàn)斷連的情況。application.properties配置如下(此坑我跳過(guò),歡迎入坑):
spring.datasource.url=jdbc:mysql://localhost/test
spring.datasource.username=dbuser
spring.datasource.password=dbpass
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
原因分析:
- mysql在默認(rèn)的情況下,如果發(fā)現(xiàn)一個(gè)連接空閑時(shí)間超過(guò)8小時(shí),將會(huì)在數(shù)據(jù)庫(kù)端自動(dòng)關(guān)閉這個(gè)連接。(mysql wait_timeout 為8小時(shí))。
解決方式:
1 . Mysql 5 版本之前可以通過(guò)在URL后面加入autoReconnect=true,如:
spring.datasource.url=jdbc:mysql://localhost/test?autoReconnect=true
2 . application.properties文件中加入:
spring.datasource.test-on-borrow=false
spring.datasource.test-while-idle=true
spring.datasource.time-between-eviction-runs-millis= 3600000
3 . 粗暴點(diǎn)的直接修改 wait_timeout 時(shí)間:
show global variables like 'wait_timeout';
Paste_Image.png