spring boot + mybatis 读写分离

本文介绍了如何在Spring Boot环境下利用MyBatis和Druid配置读写分离,通过AbstractRoutingDataSource和@Intercepts拦截器区分读写操作,并自定义DataSourceTransactionManager处理事务状态下的数据源分配。详细配置包括两个数据源、拦截器设置以及事务管理器的实现。
摘要由CSDN通过智能技术生成

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
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值