Java SpringBoot 动态数据源
在Spring Boot中配置动态数据源可以通过编程方式在运行时切换数据源。以下是一个简化的例子,展示了如何在Spring Boot应用程序中配置和切换动态数据源:
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import javax.sql.DataSource;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class DynamicDataSource extends AbstractRoutingDataSource {
private final Map<Object, Object> dynamicTargetDataSources = new ConcurrentHashMap<>();
public void addDataSource(String key, DataSource dataSource) {
this.dynamicTargetDataSources.put(key, dataSource);
this.setTargetDataSources(dynamicTargetDataSources);
this.afterPropertiesSet();
}
public void removeDataSource(String key) {
this.dynamicTargetDataSources.remove(key);
this.setTargetDataSources(dynamicTargetDataSources);
this.afterPropertiesSet();
}
@Override
protected Object determineCurrentLookupKey() {
// 返回当前线程使用的数据源标识
return DataSourceContextHolder.getDataSourceType();
}
}
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();
}
}
// 在配置类中配置动态数据源
@Configuration
public class DataSourceConfig {
@Bean
public DataSource dataSource() {
DynamicDataSource dynamicDataSource = new DynamicDataSource();
// 配置默认数据源
dynamicDataSource.setDefaultTargetDataSource(primaryDataSource());
// 初始化时添加其他数据源
dynamicDataSource.addDataSource("secondary", secondaryDataSource());
return dynamicDataSource;
}
@Bean
public DataSource primaryDataSource() {
// 配置主数据源
return ...;
}
@Bean
public DataSource secondaryDataSource() {
// 配置第二数据源
return ...;
}
// 切换数据源的方法
public void switchDataSource(String dataSourceType) {
DataSourceContextHolder.setDataSourceType(dataSourceType);
}
}
// 使用动态数据源执行操作
public class SomeService {
@Autowired
private JdbcTemplate jdbcTemplate;
public void doSomething() {
评论已关闭