在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注解即可动态切换数据源。