Spring Boot 中动态数据源配置与使用详解
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
@Configuration
public class DynamicDataSourceConfig {
@Bean
@Primary
public DataSource dynamicDataSource() {
DynamicDataSource dynamicDataSource = new DynamicDataSource();
// 配置默认数据源
dynamicDataSource.setDefaultTargetDataSource(primaryDataSource());
// 配置多数据源
Map<Object, Object> dataSourceMap = new HashMap<>();
dataSourceMap.put("primaryDataSource", primaryDataSource());
dataSourceMap.put("secondaryDataSource", secondaryDataSource());
// 设置数据源映射
dynamicDataSource.setTargetDataSources(dataSourceMap);
return dynamicDataSource;
}
@Bean(name = "primaryDataSource")
public DataSource primaryDataSource() {
return DataSourceBuilder.create()
.url("jdbc:mysql://localhost:3306/primary")
.username("root")
.password("123456")
.build();
}
@Bean(name = "secondaryDataSource")
public DataSource secondaryDataSource() {
return DataSourceBuilder.create()
.url("jdbc:mysql://localhost:3306/secondary")
.username("root")
.password("123456")
.build();
}
}
这个代码实例展示了如何在Spring Boot应用程序中配置和定义多个数据源,并通过DynamicDataSource类动态地在它们之间进行切换。这是一个简化的示例,仅包含核心配置,并假设DynamicDataSource
类已正确实现并可以处理数据源的切换逻辑。
评论已关闭