在mybatis多數(shù)據(jù)源配置下,為什么需要添加test-while-idle等參數(shù)來解決連接關(guān)閉問題?這個問題在單數(shù)據(jù)源環(huán)境下并不常見,但切換到多數(shù)據(jù)源配置后,可能會遇到”no operations allowed after connection closed”的錯誤。讓我們探討一下這個問題,并了解為什么需要這些配置。
關(guān)于MyBatis多數(shù)據(jù)源配置引發(fā)的連接關(guān)閉問題
在使用MyBatis進行數(shù)據(jù)庫操作時,切換到多數(shù)據(jù)源配置后,可能會遇到”No operations allowed after connection closed”的錯誤。之前在單數(shù)據(jù)源環(huán)境下,這種問題并未出現(xiàn)過,也沒有配置過類似test-while-idle=true的參數(shù)。那么,為什么在多數(shù)據(jù)源環(huán)境下需要這些配置呢?
在多數(shù)據(jù)源配置之前,單數(shù)據(jù)源的配置如下:
# 單數(shù)據(jù)源配置 spring.datasource.url=jdbc:mysql://localhost:3306/db1 spring.datasource.username=root spring.datasource.password=password
切換到多數(shù)據(jù)源配置后,配置變成了:
# 多數(shù)據(jù)源配置 spring.datasource.primary.url=jdbc:mysql://localhost:3306/db1 spring.datasource.primary.username=root spring.datasource.primary.password=password <p>spring.datasource.test1.url=jdbc:mysql://localhost:3306/db2 spring.datasource.test1.username=root spring.datasource.test1.password=password
然而,在多數(shù)據(jù)源環(huán)境下,出現(xiàn)了”No operations allowed after connection closed”的錯誤。網(wǎng)上搜索發(fā)現(xiàn),需要添加以下MyBatis相關(guān)的配置:
spring.datasource.primary.test-while-idle=true spring.datasource.primary.time-between-eviction-runs-millis=18000
那么,添加這些配置是否能解決問題呢?為什么在單數(shù)據(jù)源環(huán)境下不需要這些配置?
是的,添加上述配置通常能解決這個問題,特別是這些關(guān)鍵參數(shù):
spring.datasource.primary.test-while-idle=true spring.datasource.primary.time-between-eviction-runs-millis=18000
對于每個數(shù)據(jù)源,都需要類似配置:
# 主數(shù)據(jù)源 spring.datasource.primary.test-while-idle=true spring.datasource.primary.validation-query=select 1</p><h1>測試數(shù)據(jù)源</h1><p>spring.datasource.test1.test-while-idle=true spring.datasource.test1.validation-query=SELECT 1
配置說明
-
test-while-idle=true:
- 關(guān)鍵配置,讓連接池定期檢查空閑連接是否有效。
- 避免使用已關(guān)閉的連接。
-
validation-query:
- 用于測試連接是否有效的SQL。
- 通常使用輕量級查詢?nèi)?#8221;SELECT 1″。
-
time-between-eviction-runs-millis:
- 空閑連接檢查的時間間隔。
- 18000毫秒(18秒)是個合理值。
-
min-idle 和 max-idle:
- 控制連接池中保持的最小和最大空閑連接數(shù)。
為什么需要這些配置
多數(shù)據(jù)源環(huán)境下,某些數(shù)據(jù)源可能較少使用,導(dǎo)致連接長時間空閑。數(shù)據(jù)庫服務(wù)器通常會關(guān)閉長時間空閑的連接(如MySQL默認8小時)。如果應(yīng)用嘗試使用這些已關(guān)閉的連接,就會出現(xiàn)”No operations allowed after connection closed”錯誤。
通過啟用test-while-idle和設(shè)置validation-query,連接池會定期驗證連接是否有效,及時關(guān)閉無效連接并創(chuàng)建新連接,從而避免使用已關(guān)閉的連接。