SpringBoot+Dynamic多数据源动态切换以上方法再详细一点
时间: 2023-12-21 19:06:18 浏览: 45
好的,下面我来详细介绍一下 SpringBoot+Dynamic 多数据源动态切换的实现方法。
1. 添加依赖
在 pom.xml 文件中添加以下依赖:
```xml
<!-- MyBatis Plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.2</version>
</dependency>
<!-- Druid 数据源 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.6</version>
</dependency>
<!-- Dynamic DataSource -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>2.5.3</version>
</dependency>
```
2. 配置数据源
在 application.yml 文件中配置数据源信息:
```yaml
spring:
datasource:
druid:
driver-class-name: com.mysql.jdbc.Driver
initial-size: 5
max-active: 10
min-idle: 3
filters: stat,wall,slf4j
# 主数据源
master:
url: jdbc:mysql://localhost:3306/db_master?useUnicode=true&characterEncoding=utf8&useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC
username: root
password: 123456
# 从数据源
slave:
url: jdbc:mysql://localhost:3306/db_slave?useUnicode=true&characterEncoding=utf8&useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC
username: root
password: 123456
```
3. 配置 DynamicDataSource
在 SpringBoot 启动类上添加 @EnableDynamicDataSource 注解,开启动态数据源功能:
```java
@SpringBootApplication
@EnableDynamicDataSource
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
```
4. 配置 MyBatis Plus
在 MyBatis Plus 的配置文件中添加以下配置:
```java
@Configuration
@MapperScan("com.example.demo.mapper")
public class MybatisPlusConfig {
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new DynamicTableNameInnerInterceptor(new TableNameParser() {
@Override
public String parse(String tableName) {
// 根据业务需求动态返回表名
return tableName;
}
}));
return interceptor;
}
}
```
5. 编写动态数据源切换逻辑
在需要切换数据源的地方,通过 DynamicDataSourceContextHolder 切换数据源:
```java
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public List<User> getUserList() {
// 切换到从数据源
DynamicDataSourceContextHolder.setDataSourceKey("slave");
List<User> userList = userMapper.selectList(null);
// 切换回主数据源
DynamicDataSourceContextHolder.setDataSourceKey("master");
return userList;
}
}
```
6. 测试
启动 SpringBoot 项目,调用 getUserList 方法,查看控制台输出日志,可以看到动态切换数据源的日志信息。
以上就是 SpringBoot+Dynamic 多数据源动态切换的详细实现方法。