springboot集成动态数据源
时间: 2023-11-09 07:01:50 浏览: 85
springboot集成多数据源
在Spring Boot中集成动态数据源,可以使用第三方库Dynamic DataSource Routing或Spring提供的AbstractRoutingDataSource类来实现。其中Dynamic DataSource Routing提供了更加灵活的配置方式,可以根据需要动态切换数据源。
使用Dynamic DataSource Routing的步骤如下:
1. 引入依赖:在pom.xml文件中添加以下依赖
```
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>2.5.3</version>
</dependency>
```
2. 配置数据源:在application.yml文件中配置数据源信息,可以配置多个数据源
```
spring:
datasource:
dynamic:
datasource:
master:
url: jdbc:mysql://localhost:3306/master?useUnicode=true&characterEncoding=utf-8&useSSL=false
username: root
password: root
slave1:
url: jdbc:mysql://localhost:3306/slave1?useUnicode=true&characterEncoding=utf-8&useSSL=false
username: root
password: root
slave2:
url: jdbc:mysql://localhost:3306/slave2?useUnicode=true&characterEncoding=utf-8&useSSL=false
username: root
password: root
primary: master
```
3. 配置动态数据源:在配置类中添加以下代码
```
@Configuration
public class DynamicDataSourceConfig {
@Bean
@ConfigurationProperties("spring.datasource.druid.master")
public DataSource masterDataSource() {
return DruidDataSourceBuilder.create().build();
}
@Bean
@ConfigurationProperties("spring.datasource.druid.slave1")
public DataSource slave1DataSource() {
return DruidDataSourceBuilder.create().build();
}
@Bean
@ConfigurationProperties("spring.datasource.druid.slave2")
public DataSource slave2DataSource() {
return DruidDataSourceBuilder.create().build();
}
@Bean
public DynamicDataSource dynamicDataSource() {
Map<Object, Object> targetDataSources = new HashMap<>(); targetDataSources.put("master", masterDataSource());
targetDataSources.put("slave1", slave1DataSource());
targetDataSources.put("slave2", slave2DataSource());
return new DynamicDataSource(masterDataSource(), targetDataSources);
}
}
```
4. 使用动态数据源:在需要使用数据源的地方,使用@DS注解指定数据源
```
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@DS("slave1")
@Override
public List<User> listUsers() {
return userMapper.listUsers();
}
@DS("slave2")
@Override
public User getUserById(Long id) {
return userMapper.getUserById(id);
}
@DS("master")
@Override
public void saveUser(User user) {
userMapper.saveUser(user);
}
}
```
阅读全文