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