這個問題涉及的方面很多,需要一步步去排查,可能環境有問題,數據庫有問題,但是網上最多的應該是如下的方式去解決。
以單個數據源為主,多個數據源基本方法一致。
1、MySQL 5版本之前可以通過在URL后面加入autoReconnect=true,如:
spring.datasource.url=jdbc:mysql://localhost/test?autoReconnect=true
2、application.properties文件中加入:
spring.datasource.test-on-borrow=true #(即在獲取Connection對象時檢測其可用性),不過這樣會影響性能,但是這個配置是最有效的。
spring.datasource.test-while-idle=true
spring.datasource.time-between-eviction-runs-millis= 3600000
3、粗暴點的直接修改wait_timeout時間:
show global variables like 'wait_timeout';
推薦使用第2種,從配置項入手。
網上有這塊的詳細解釋:
datasource.qss.max-idle=10 # Number of ms to wait before throwing an exception if no connection is available. datasource.qss.max-wait=10000 datasource.qss.min-idle=5 datasource.qss.initial-size=5 # Maximum number of active connections that can be allocated from this pool at the same time. datasource.qss.max-active=100 datasource.qss.validation-query=SELECT 1 #使用testOnBorrow為true(即在獲取Connection對象時檢測其可用性),不過這樣會影響性能 # Validate the connection before borrowing it from the pool. datasource.qss.test-on-borrow=true #有些數據庫連接的時候有超時限制(mysql連接在8小時后斷開),或者由於網絡中斷等原因,連接池的連接會出現失效的情況,這時候設置一個testWhileIdle參數為true,可以保證連接池內部定時檢測連接的可用性,不可用的連接會被拋棄或者重建,最大情況的保證從連接池中得到的Connection對象是可用的。 datasource.qss.test-while-idle=true #設置當連接被歸還時,是否要提交所有還未完成的事務 datasource.qss.test-on-return=false #如果當前連接池中某個連接在空閑了timeBetweenEvictionRunsMillis時間后任然沒有使用,則被物理性的關閉掉。 datasource.qss.time-between-eviction-runs-millis=60000 # 配置一個連接在池中最小生存的時間,單位是毫秒 datasource.qss.min-evictable-idle-time-millis=300000 datasource.qss.jdbc-interceptors=ConnectionState;SlowQueryReport(threshold=0)
總之,要不斷嘗試發現問題來解決,上述方式不一定准確。可能代碼問題,可以配置問題,也可能是數據庫的問題;
參考:
http://m.jb51.net/article/108955.htm(以上內容轉自此篇文章)
http://blog.csdn.net/return__null/article/details/51589038
http://www.jianshu.com/p/c642a83a1ec7(以上小部分配置轉自此篇文章)
http://www.jianshu.com/p/1626d41572f2
http://soberchina.iteye.com/blog/2355289
http://www.ijianbian.com/home/post/detail?id=6201338
http://blog.csdn.net/neosmith/article/details/61202084
https://www.cnblogs.com/java-zhao/p/5413845.html
https://www.cnblogs.com/ityouknow/p/6102399.html
http://www.jianshu.com/p/34730e595a8c
http://confluence.goldpitcher.co.kr/pages/viewpage.action?pageId=136317019
http://xdjava.iteye.com/blog/1525148