0.动态数据源 官网:https://dynamic-datasource.com/
1.导入jar
<!--引入 MyBatis-Plus 之后请不要再次引入 MyBatis 以及 MyBatis-Spring,以避免因版本差异导致的问题-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>3.3.1</version>
</dependency>
2.配置 yml
spring:
datasource:
dynamic:
primary: master #设置默认的数据源或者数据源组,默认值即为master
strict: true #设置严格模式,默认false不启动. 启动后在未匹配到指定数据源时候会抛出异常,不启动则使用默认数据源.
datasource:
master: # @DS("存放的字符串类型")
url: jdbc:mysql://127.0.0.1:3306/xxxx?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai&allowMultiQueries=true&zeroDateTimeBehavior=CONVERT_TO_NULL
username: xxx
password: xxx
driver-class-name: com.mysql.jdbc.Driver
slave: # @DS("存放的字符串类型")
url: jdbc:mysql://127.0.0.1:3306/xxxx?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai&allowMultiQueries=true&zeroDateTimeBehavior=CONVERT_TO_NULL
username: xxx
password: xxx
driver-class-name: com.mysql.jdbc.Driver
druid:
filters: stat
max-active: 20
max-wait: 60000
time-between-eviction-runs-millis: 60000
validation-query: select 'x'
test-while-idle: true
test-on-borrow: false
test-on-return: false
pool-prepared-statements: false
max-pool-prepared-statement-per-connection-size: 20
3.创建配置相关 bean
@Bean
public MasterSlaveAutoRoutingPlugin masterSlaveAutoRoutingPlugin(){
return new MasterSlaveAutoRoutingPlugin();
}
4.在 mapper和service层 使用
@DS("slave")可以配置在方法及类上
@DS("master")可以配置在方法及类上
5.原理 主要应用springboot 装配原理姐 aop的思想
DynamicDataSourceAutoConfiguration 自动装配->