在MyBatis多数据源环境下,为什么会出现"No operations allowed after connection closed"错误?添加哪些配置能解决这个问题?

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

配置说明

  1. test-while-idle=true

    • 关键配置,让连接池定期检查空闲连接是否有效。
    • 避免使用已关闭的连接。
  2. validation-query

    • 用于测试连接是否有效的SQL。
    • 通常使用轻量级查询如”SELECT 1″。
  3. time-between-eviction-runs-millis

    • 空闲连接检查的时间间隔。
    • 18000毫秒(18秒)是个合理值。
  4. min-idlemax-idle

    • 控制连接池中保持的最小和最大空闲连接数。

为什么需要这些配置

多数据源环境下,某些数据源可能较少使用,导致连接长时间空闲。数据库服务器通常会关闭长时间空闲的连接(如MySQL默认8小时)。如果应用尝试使用这些已关闭的连接,就会出现”No operations allowed after connection closed”错误。

通过启用test-while-idle和设置validation-query,连接池会定期验证连接是否有效,及时关闭无效连接并创建新连接,从而避免使用已关闭的连接。

在MyBatis多数据源环境下,为什么会出现"No operations allowed after connection closed"错误?添加哪些配置能解决这个问题?

© 版权声明
THE END
喜欢就支持一下吧
点赞14 分享