spring boot + mybatis read/write splitting
参考:https://blog.csdn.net/wuyongde_0922/article/details/70655185 方案4
总体的思路:AbstractRoutingDataSource + mybatis @Intercepts + DataSourceTransactionManager
主体的判断逻辑均来自上述博文,这里仅描述在springboot环境下的配置方式。
使用版本:
- spring boot:2.0.2.RELEASE
- mybatis.starter:1.3.1
- druid:1.1.9
- mysql:5.7
1. 配置两个数据源,这里使用druid
# application.yml (mybatis配置)
spring:
profiles:
# 使用开发环境
active: dev
mybatis:
configuration:
# 驼峰转换
map-underscore-to-camel-case: true
# 默认缓存数量
default-fetch-size: 100
# SQL执行的超时时间
default-statement-timeout: 3000
# 日志输出到控制台
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
# application-dev.yml (数据源配置)
write:
datasource:
username: root
password: 123123
url: jdbc:mysql://localhost:3306/db1?useSSL=false&useUnicode=true&characterEncoding=utf8
# 最大连接数
maxActive: 1000
# 连接池初始化大小
initialSize: 100
# 获取连接的最大等待时间,单位毫秒
maxWait: 60000
# 最小保留数
minIdle: 500
# 检测关闭空闲连接的间隔时间,单位毫秒
timeBetweenEvictionRunsMillis: 60000
# 连接的最小生存时间,,单位毫秒
minEvictableIdleTimeMillis: 300000
validationQuery: select 1
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
# 打开PSCache,并且指定每个连接上PSCache的大小
poolPreparedStatements: true
maxOpenPreparedStatements: 20
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
filters: stat, wall, slf4j
# 合并多个DruidDataSource的监控数据
useGlobalDataSourceStat: true
read:
datasource:
username: root
password: 123123
url: jdbc:mysql://localhost:3306/db2?useSSL=false&useUnicode=true&characterEncoding=utf8
# 最大连接数
maxActive: 1000
# 连接池初始化大小
initialSize: 100
# 获取连接的最大等待时间,单位毫秒
maxWait: 60000
# 最小保留数
minIdle: 500
# 检测关闭空闲连接的间隔时间,单位毫秒
timeBetweenEvictionRunsMillis: 60000
# 连接的最小生存时间,,单位毫秒
minEvictableIdleTimeMillis: 300000
validationQuery: select 1
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
# 打开PSCache,并且指定每个连接上PSCache的大小
poolPreparedStatements: true
maxOpenPreparedStatements: 20
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
filters: stat, wall, slf4j
# 合并多个DruidDataSource的监控数据
useGlobalDataSourceS