SpringBoot中的DynamicDataSource 如何实现读写分离
时间: 2024-05-02 09:22:11 浏览: 105
SpringBoot中的DynamicDataSource可以通过配置多个数据源来实现读写分离。
首先,在application.yml中配置多个数据源:
```
spring:
datasource:
master:
url: jdbc:mysql://localhost:3306/master?useUnicode=true&characterEncoding=utf8&useSSL=false
username: root
password: 123456
slave:
url: jdbc:mysql://localhost:3306/slave?useUnicode=true&characterEncoding=utf8&useSSL=false
username: root
password: 123456
```
然后,在DynamicDataSource类中实现AbstractRoutingDataSource接口,并重写determineCurrentLookupKey方法,根据业务需求动态切换数据源:
```
public class DynamicDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
return DataSourceContextHolder.getDataSourceKey();
}
}
```
最后,在启动类中配置DynamicDataSource,并设置默认数据源:
```
@SpringBootApplication
public class Application {
@Bean
@ConfigurationProperties("spring.datasource.master")
public DataSource masterDataSource() {
return DataSourceBuilder.create().build();
}
@Bean
@ConfigurationProperties("spring.datasource.slave")
public DataSource slaveDataSource() {
return DataSourceBuilder.create().build();
}
@Bean
public DynamicDataSource dynamicDataSource() {
Map<Object, Object> targetDataSources = new HashMap<>();
targetDataSources.put(DataSourceType.MASTER, masterDataSource());
targetDataSources.put(DataSourceType.SLAVE, slaveDataSource());
DynamicDataSource dynamicDataSource = new DynamicDataSource();
dynamicDataSource.setTargetDataSources(targetDataSources);
dynamicDataSource.setDefaultTargetDataSource(masterDataSource()); // 默认数据源为master
return dynamicDataSource;
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
```
在业务代码中,通过设置DataSourceContextHolder中的数据源key,就可以实现动态切换数据源:
```
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public void addUser(User user) {
DataSourceContextHolder.setDataSourceKey(DataSourceType.MASTER);
userMapper.addUser(user);
}
public User getUserById(int id) {
DataSourceContextHolder.setDataSourceKey(DataSourceType.SLAVE);
return userMapper.getUserById(id);
}
}
```
阅读全文