SpringBoot实现多数据源切换
在Spring Boot中实现多数据源切换,可以通过定义多个数据源配置,并使用AbstractRoutingDataSource
来实现动态数据源的路由。以下是一个简化的例子:
- 定义数据源配置类:
@Configuration
public class DataSourceConfig {
@Bean
@ConfigurationProperties("spring.datasource.primary")
public DataSource primaryDataSource() {
return DataSourceBuilder.create().build();
}
@Bean
@ConfigurationProperties("spring.datasource.secondary")
public DataSource secondaryDataSource() {
return DataSourceBuilder.create().build();
}
}
- 定义动态数据源:
public class RoutingDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
return DataSourceContext.getCurrentDataSource();
}
}
- 使用ThreadLocal来保存当前数据源标识:
public class DataSourceContext {
private static final ThreadLocal<String> contextHolder = new ThreadLocal<>();
public static void setCurrentDataSource(String dataSourceType) {
contextHolder.set(dataSourceType);
}
public static String getCurrentDataSource() {
return contextHolder.get();
}
public static void clearDataSource() {
contextHolder.remove();
}
}
- 配置动态数据源:
@Configuration
public class DynamicDataSourceConfig {
@Primary
@Bean
public DataSource dynamicDataSource(@Qualifier("primaryDataSource") DataSource primaryDataSource,
@Qualifier("secondaryDataSource") DataSource secondaryDataSource) {
RoutingDataSource routingDataSource = new RoutingDataSource();
Map<Object, Object> dataSourceMap = new HashMap<>();
dataSourceMap.put("primary", primaryDataSource);
dataSourceMap.put("secondary", secondaryDataSource);
routingDataSource.setTargetDataSources(dataSourceMap);
routingDataSource.setDefaultTargetDataSource(primaryDataSource);
return routingDataSource;
}
}
- 使用数据源切换:
@Service
public class DataSourceService {
@Autowired
private JdbcTemplate primaryJdbcTemplate;
@Autowired
private JdbcTemplate secondaryJdbcTemplate;
public void usePrimaryDataSource() {
DataSourceContext.setCurrentDataSource("primary");
评论已关闭