springboot druid mybatis 多数据源 示例
时间: 2023-05-23 14:03:02 浏览: 128
您可以参考以下代码示例:
@Configuration
@MapperScan(basePackages = "com.example.demo.mapper")
public class DataSourceConfig {
@Bean(name = "db1")
@ConfigurationProperties(prefix = "spring.datasource.db1")
public DataSource dataSourceDB1() {
return DataSourceBuilder.create().build();
}
@Bean(name = "db2")
@ConfigurationProperties(prefix = "spring.datasource.db2")
public DataSource dataSourceDB2() {
return DataSourceBuilder.create().build();
}
@Bean(name = "db3")
@ConfigurationProperties(prefix = "spring.datasource.db3")
public DataSource dataSourceDB3() {
return DataSourceBuilder.create().build();
}
@Bean
@Primary
public DynamicDataSource dataSource() {
Map<Object, Object> targetDataSources = new HashMap<>();
targetDataSources.put("db1", dataSourceDB1());
targetDataSources.put("db2", dataSourceDB2());
targetDataSources.put("db3", dataSourceDB3());
DynamicDataSource dataSource = new DynamicDataSource();
dataSource.setTargetDataSources(targetDataSources);
dataSource.setDefaultTargetDataSource(dataSourceDB1());
return dataSource;
}
}
然后我们需要实现 DynamicDataSource,继承自 AbstractRoutingDataSource,只需要实现如何获取当前数据源的代码:
public class DynamicDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
return DataSourceContextHolder.getDataSource();
}
}
最后,我们需要定义一个 DataSourceContextHolder 来存储当前的数据源标识:
public class DataSourceContextHolder {
private static final ThreadLocal<String> contextHolder = new ThreadLocal<>();
public static void setDataSource(String dataSource) {
contextHolder.set(dataSource);
}
public static String getDataSource() {
return contextHolder.get();
}
public static void clear() {
contextHolder.remove();
}
}
这样我们就可以在需要切换数据源的时候,调用 DataSourceContextHolder.setDataSource("db1") 或 DataSourceContextHolder.setDataSource("db2") 即可。
阅读全文