在MyBatis多數(shù)據(jù)源環(huán)境下,為什么會(huì)出現(xiàn)"No operations allowed after connection closed"錯(cuò)誤?添加哪些配置能解決這個(gè)問題?

mybatis多數(shù)據(jù)源環(huán)境下,如何解決”no operations allowed after connection closed”錯(cuò)誤?

在使用MyBatis進(jìn)行數(shù)據(jù)庫(kù)操作時(shí),切換到多數(shù)據(jù)源配置后,可能會(huì)遇到”No operations allowed after connection closed”錯(cuò)誤。之前在單數(shù)據(jù)源配置下,這種問題并未出現(xiàn),相關(guān)的配置參數(shù)如test-while-idle=true也未曾設(shè)置過。那么,在多數(shù)據(jù)源配置下,為什么會(huì)出現(xiàn)這個(gè)問題??jī)H僅添加一些配置就能解決嗎?

在多數(shù)據(jù)源環(huán)境下,當(dāng)切換到如下的配置后:

# 主數(shù)據(jù)源配置 spring.datasource.primary.jdbc-url=jdbc:mysql://localhost:3306/db1 spring.datasource.primary.username=root spring.datasource.primary.password=password <h1>測(cè)試數(shù)據(jù)源配置</h1><p>spring.datasource.test1.jdbc-url=jdbc:mysql://localhost:3306/db2 spring.datasource.test1.username=root spring.datasource.test1.password=password

開始出現(xiàn)”No operations allowed after connection closed”錯(cuò)誤。網(wǎng)上建議添加以下MyBatis相關(guān)的配置:

spring.datasource.primary.test-while-idle=true spring.datasource.primary.time-between-eviction-runs-millis=18000

那么,僅僅添加這些配置就能解決問題嗎?為什么單數(shù)據(jù)源配置時(shí)不需要這些配置?

是的,添加如下的配置通常能夠解決這個(gè)問題,特別是這些關(guān)鍵參數(shù):

spring.datasource.primary.test-while-idle=true spring.datasource.primary.time-between-eviction-runs-millis=18000

對(duì)于每個(gè)數(shù)據(jù)源都需要類似的配置:

# 主數(shù)據(jù)源 spring.datasource.primary.test-while-idle=true spring.datasource.primary.validation-query=select 1</p><h1>測(cè)試數(shù)據(jù)源</h1><p>spring.datasource.test1.test-while-idle=true spring.datasource.test1.validation-query=SELECT 1

配置說明

  1. test-while-idle=true

    • 關(guān)鍵配置,讓連接池定期檢查空閑連接是否有效。
    • 避免使用已關(guān)閉的連接。
  2. validation-query

    • 用于測(cè)試連接是否有效的SQL。
    • 通常使用輕量級(jí)查詢?nèi)?#8221;SELECT 1″。
  3. time-between-eviction-runs-millis

    • 空閑連接檢查的時(shí)間間隔。
    • 18000毫秒(18秒)是個(gè)合理值。
  4. min-idlemax-idle

    • 控制連接池中保持的最小和最大空閑連接數(shù)。

為什么需要這些配置

多數(shù)據(jù)源環(huán)境下,某些數(shù)據(jù)源可能較少使用,導(dǎo)致連接長(zhǎng)時(shí)間空閑。數(shù)據(jù)庫(kù)服務(wù)器通常會(huì)關(guān)閉長(zhǎng)時(shí)間空閑的連接(如MySQL默認(rèn)8小時(shí))。如果應(yīng)用嘗試使用這些已關(guān)閉的連接,就會(huì)出現(xiàn)”No operations allowed after connection closed”錯(cuò)誤。

通過啟用test-while-idle和設(shè)置validation-query,連接池會(huì)定期驗(yàn)證連接是否有效,及時(shí)關(guān)閉無效連接并創(chuàng)建新連接,從而避免使用已關(guān)閉的連接。

在MyBatis多數(shù)據(jù)源環(huán)境下,為什么會(huì)出現(xiàn)"No operations allowed after connection closed"錯(cuò)誤?添加哪些配置能解決這個(gè)問題?

? 版權(quán)聲明
THE END
喜歡就支持一下吧
點(diǎn)贊14 分享