Spring Boot數據源配置及No operations allowed after connection closed連接異常的解決
首先說下我的項目配置: SpringBooot + SpringMVC+SpringData JPA+ MySql
前期開發是沒什麼問題的,一切運轉良好。但是今天我又測試了一遍,居然報了以下錯誤:
注意排查異常要抓住重點: No operations allowed after connection closed。
從這個地方我們知道是mysql的鏈接關閉了已經。訪問一個關閉了的鏈接當然會出現異常了。
原因:
之所以會出現這個異常,是因爲MySQL5.0以後針對超長時間DB連接做了一個處理,那就是如果一個DB連接在無任何操作情況下過了8個小時後(Mysql 服務器默認的“wait_timeout”是8小時),Mysql會自動把這個連接關閉。這就是問題的所在,在連接池中的connections如果空閒超過8小時,mysql將其斷開,而連接池自己並不知道該connection已經失效,如果這時有 Client請求connection,連接池將該失效的Connection提供給Client,將會造成上面的異常。
所以配置datasource時需要配置相應的連接池參數,定是去檢查連接的有效性,定時清理無效的連接。
那解決方法是什麼呢?
在application.properties的兩個數據源的配置下添加如下連接池配置:
#以下爲連接池的相關參數配置
spring.datasource.max-idle=10
spring.datasource.max-wait=10000
spring.datasource.min-idle=5
spring.datasource.initial-size=5
spring.datasource.validation-query=SELECT 1
spring.datasource.test-on-borrow=false
spring.datasource.test-while-idle=true
spring.datasource.time-between-eviction-runs-millis=18800
補充:spring boot默認會優先使用的連接池是tomcat連接池,前提是在tomcat連接池可用的情況下