Spring Boot + Mybatis 多数据源配置实现读写分离
应用场景:项目中有一些报表统计与查询功能,对数据实时性要求不高,因此考虑对报表的统计与查询去操作slave db,减少对master的压力。
根据网上多份资料测试发现总是使用master数据源,无法切换到slave,经过多次调试修改现已完美通过,现整理下详细步骤和完整代码如下:
实现方式:配置多个数据源,使用Spring AOP实现拦截注解实现数据源的动态切换。
- application.yml数据库配置:
spring:
tomcat:
max-threads: 1000
accept-count: 10000
datasource:
druid:
type: com.alibaba.druid.pool.DruidDataSource
master:
driver-class-name: com.mysql.cj.jdbc.Driver
initialSize: 10
minIdle: 1
maxActive: 1000
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 30000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
#exceptionSorter: true
testOnReturn: false
poolPreparedStatements: true
filter: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
useGlobalDataSourceStat: true
url: jdbc:mysql://你的数据库地址:3306/你的库名?useUnicode=true&characterEncoding=utf-8&useSSL=false
username: root
password: ********
slave:
driver-class-name: com.mysql.cj.jdbc.Driver
initialSize: 10
minIdle: 1
maxActive: 1000
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 30000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
#exceptionSorter: true
testOnReturn: false
poolPreparedStatements: true
filter: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
useGlobalDataSourceStat: true
url: jdbc:mysql://你的数据库地址:3306/库名?useUnicode=true&characterEncoding=utf-8&useSSL=false
username: root
password: *******
Mybatis
mybatis:
typeAliasesPackage: com.sxchain.notary.persistence
mapperLocations: classpath:mapper/*.xml
configuration:
map-underscore-to-camel-case: true
server:
port: 8083
打印sql
logging:
level:
root: info #日志配置DEBUG,INFO,WARN,ERROR
com.sxchain.notary.persistence : debug
path: /var/logs
2. 实现多数据源注入:
package com.sxchain.notary.config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annota