在Spring Boot中配置動態數據源需要使用多數據源配置。以下是配置動態數據源的步驟:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
</dependency>
@Configuration
public class DataSourceConfig1 {
@Bean(name = "dataSource1")
@ConfigurationProperties(prefix = "spring.datasource.ds1")
public DataSource dataSource1() {
return DataSourceBuilder.create().build();
}
}
@Configuration
public class DataSourceConfig2 {
@Bean(name = "dataSource2")
@ConfigurationProperties(prefix = "spring.datasource.ds2")
public DataSource dataSource2() {
return DataSourceBuilder.create().build();
}
}
@Configuration
public class DynamicDataSourceConfig {
@Bean
@Primary
public DataSource dynamicDataSource(@Qualifier("dataSource1") DataSource dataSource1,
@Qualifier("dataSource2") DataSource dataSource2) {
DynamicRoutingDataSource dynamicDataSource = new DynamicRoutingDataSource();
Map<Object, Object> dataSourceMap = new HashMap<>();
dataSourceMap.put("dataSource1", dataSource1);
dataSourceMap.put("dataSource2", dataSource2);
dynamicDataSource.setDefaultTargetDataSource(dataSource1);
dynamicDataSource.setTargetDataSources(dataSourceMap);
return dynamicDataSource;
}
}
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 clearDataSource() {
contextHolder.remove();
}
}
@Aspect
@Component
public class DataSourceAspect {
@Pointcut("@annotation(com.example.demo.annotation.DataSource)")
public void dataSourcePointcut() {
}
@Before("dataSourcePointcut() && @annotation(dataSource)")
public void switchDataSource(JoinPoint joinPoint, DataSource dataSource) {
DataSourceContextHolder.setDataSource(dataSource.value());
}
@After("dataSourcePointcut()")
public void restoreDataSource(JoinPoint joinPoint) {
DataSourceContextHolder.clearDataSource();
}
}
@DataSource("dataSource2")
public void test() {
// 方法體
}
通過以上步驟,就可以實現在Spring Boot中配置動態數據源。在需要切換數據源的方法上添加@DataSource注解即可動態切換數據源。