springboot读写分离配置
时间: 2024-03-07 22:45:49 浏览: 145
在Spring Boot中实现读写分离配置可以通过使用多数据源和动态数据源的方式来实现。下面是一种常见的配置方式:
1. 配置多个数据源:在`application.properties`或`application.yml`文件中配置多个数据源的连接信息,例如:
```
spring.datasource.master.url=jdbc:mysql://localhost:3306/masterdb
spring.datasource.master.username=root
spring.datasource.master.password=123456
spring.datasource.slave.url=jdbc:mysql://localhost:3306/slavedb
spring.datasource.slave.username=root
spring.datasource.slave.password=123456
```
2. 创建数据源配置类:创建一个配置类,用于配置多个数据源,并将其注入到Spring容器中,例如:
```java
@Configuration
public class DataSourceConfig {
@Bean(name = "masterDataSource")
@ConfigurationProperties(prefix = "spring.datasource.master")
public DataSource masterDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "slaveDataSource")
@ConfigurationProperties(prefix = "spring.datasource.slave")
public DataSource slaveDataSource() {
return DataSourceBuilder.create().build();
}
}
```
3. 创建动态数据源:创建一个动态数据源类,用于根据需要选择使用哪个数据源,例如:
```java
public class DynamicDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
return DataSourceContextHolder.getDataSourceType();
}
}
```
4. 配置动态数据源:在配置类中配置动态数据源,并将多个数据源添加到动态数据源中,例如:
```java
@Configuration
public class DynamicDataSourceConfig {
@Autowired
@Qualifier("masterDataSource")
private DataSource masterDataSource;
@Autowired
@Qualifier("slaveDataSource")
private DataSource slaveDataSource;
@Bean
public DynamicDataSource dynamicDataSource() {
DynamicDataSource dynamicDataSource = new DynamicDataSource(); Map<Object, Object> dataSourceMap = new HashMap<>();
dataSourceMap.put("master", masterDataSource);
dataSourceMap.put("slave", slaveDataSource);
dynamicDataSource.setTargetDataSources(dataSourceMap);
dynamicDataSource.setDefaultTargetDataSource(masterDataSource);
return dynamicDataSource;
}
@Bean
public SqlSessionFactory sqlSessionFactory(DynamicDataSource dynamicDataSource) throws Exception {
SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
sessionFactoryBean.setDataSource(dynamicDataSource);
return sessionFactoryBean.getObject();
}
}
```
5. 配置数据源切换:创建一个数据源上下文类,用于在不同的线程中切换数据源,例如:
```java
public class DataSourceContextHolder {
private static final ThreadLocal<String> contextHolder = new ThreadLocal<>();
public static void setDataSourceType(String dataSourceType) {
contextHolder.set(dataSourceType);
}
public static String getDataSourceType() {
return contextHolder.get();
}
public static void clearDataSourceType() {
contextHolder.remove();
}
}
```
6. 使用注解切换数据源:在需要切换数据源的方法上使用`@DataSource`注解,例如:
```java
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
@DataSource("master")
public User getMasterUserById(Long id) {
return userMapper.getById(id);
}
@DataSource("slave")
public User getSlaveUserById(Long id) {
return userMapper.getById(id);
}
}
```
阅读全文