Springboot、MyBatis-Plus 多数据源支持
随着项目规模的扩大,单一数据源已无法满足复杂业务需求,多数据源(动态数据源)应运而生。本文介绍MyBatis-Plus 的多数据源扩展插件 -- dynamic-datasource。
# dynamic-datasource
dynamic-datasource
是一个开源的 Spring Boot 多数据源启动器,提供了丰富的功能,包括数据源分组、敏感信息加密、独立初始化表结构等。
# 特性
- 数据源分组:适用于多种场景,如读写分离、一主多从等。
- 敏感信息加密:使用
ENC()
加密数据库配置信息。 - 独立初始化:支持每个数据库独立初始化表结构和数据库。
- 自定义注解:支持自定义注解,需继承
DS
。 - 简化集成:提供对 Druid、HikariCP 等连接池的快速集成。
- 组件集成:支持 Mybatis-Plus、Quartz 等组件的集成方案。
- 动态数据源:支持项目启动后动态增加或移除数据源。
- 分布式事务:提供基于 Seata 的分布式事务方案。
# 使用方法
引入包,并排查冲突的jar包
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>3.5.2</version>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</exclusion>
</exclusions>
</dependency>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
配置数据源:
spring:
datasource:
dynamic:
primary: master
strict: false
datasource:
master:
url: jdbc:mysql://xx.xx.xx.xx:3306/dynamic
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
slave_1:
url: jdbc:mysql://xx.xx.xx.xx:3307/dynamic
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
db2:
url: ENC(xxxxx)
username: ENC(xxxxx)
password: ENC(xxxxx)
driver-class-name: com.mysql.jdbc.Driver
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
使用 @DS 切换数据源:
@DS 可以注解在方法上或类上,同时存在就近原则 方法上注解 优先于 类上注解。 @DS(“dsName”) dsName可以为组名也可以为具体某个库的名称;
@Service
@DS("slave")
public class UserServiceImpl implements UserService {
@Autowired
private JdbcTemplate jdbcTemplate;
public List selectAll() {
return jdbcTemplate.queryForList("select * from user");
}
@Override
@DS("slave_1")
public List selectByCondition() {
return jdbcTemplate.queryForList("select * from user where age >10");
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
对于Mapper也同样适用:
如果同一类中使用一个数据源,可以在类上添加@DS
@Service
@Slf4j
@DS("master")
public class APIServiceImpl implements APIService {
@Autowired
private MeterMapper meterMapper;
}
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
上次更新: 2024/06/28, 16:57:29