mybatis-plus 多数据源
1、导入多数据源包
<!--dynamic-datasource-多数据源-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>2.5.4</version>
</dependency>
2、在service或mapper中增加注解 @DS("数据源名称")
在service中
/**
* <p>
* 服务类
* </p>
*
* @author c.luo
* @since 2021-12-06
*/
@DS("slave")
public interface DaodingTableService extends IService<DaodingTable> {
}
在mapper中
/**
* <p>
* Mapper 接口
* </p>
*
* @author c.luo
* @since 2021-12-06
*/
@DS("")
public interface DaodingTableMapper extends BaseMapper<DaodingTable> {
}
注意:如果在service中使用该注解只有调用service方法的时候才会生效
如果在mapper中使用该注解只有在调用mapper方法时才会生效
该注解在和事务注解联合使用时 该注解会失效
3、数据源配置
spring:
datasource:
dynamic:
primary: master #设置默认的数据源或者数据源组,默认值即为master,如果读者只是单数据源只需要注释掉slave相关配置即可,这里为了方便演示master与slave保持相同
datasource:
master:
url: jdbc:mysql://xxxxx:3306/xx?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true
username: root
password:
driverClassName: com.mysql.cj.jdbc.Driver
slave:
url: jdbc:mysql://xxxxx:3306/xx?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true
username: root
password:
driverClassName: com.mysql.cj.jdbc.Driver
initial-size: 10 # 以下是连接池配置
max-active: 100
min-idle: 10
max-wait: 60000
pool-prepared-statements: true
max-pool-prepared-statement-per-connection-size: 20
time-between-eviction-runs-millis: 60000
min-evictable-idle-time-millis: 300000
test-while-idle: true
test-on-borrow: false
test-on-return: false
stat-view-servlet:
enabled: true
url-pattern: /druid/*
login-username: druid
login-password: 123456
filter:
stat:
log-slow-sql: true
slow-sql-millis: 1000
merge-sql: false
wall:
config:
multi-statement-allow: true