Spring Boot的动态数据源配置
时间: 2023-08-23 21:11:20 浏览: 98
Spring Boot支持动态数据源配置,可以根据需要动态地切换数据源。以下是动态数据源配置的步骤:
1. 在pom.xml文件中添加依赖:
```xml
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
```
2. 配置数据源,在application.properties文件中添加以下配置:
```properties
spring.datasource.hikari.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.hikari.jdbc-url=jdbc:mysql://localhost:3306/db?characterEncoding=UTF-8&serverTimezone=UTC
spring.datasource.hikari.username=root
spring.datasource.hikari.password=123456
```
3. 创建多个数据源,在配置类中添加以下配置:
```java
@Configuration
public class DataSourceConfig {
@Bean(name = "dataSource1")
@ConfigurationProperties(prefix = "spring.datasource.hikari.datasource1")
public DataSource dataSource1() {
return DataSourceBuilder.create().type(HikariDataSource.class).build();
}
@Bean(name = "dataSource2")
@ConfigurationProperties(prefix = "spring.datasource.hikari.datasource2")
public DataSource dataSource2() {
return DataSourceBuilder.create().type(HikariDataSource.class).build();
}
}
```
4. 创建动态数据源,在配置类中添加以下配置:
```java
@Configuration
public class DynamicDataSourceConfig {
@Bean(name = "dynamicDataSource")
public DynamicDataSource dynamicDataSource(@Qualifier("dataSource1") DataSource dataSource1,
@Qualifier("dataSource2") DataSource dataSource2) {
Map<Object, Object> targetDataSources = new HashMap<>();
targetDataSources.put("dataSource1", dataSource1);
targetDataSources.put("dataSource2", dataSource2);
return new DynamicDataSource(dataSource1, targetDataSources);
}
}
```
5. 创建动态数据源切换类,在配置类中添加以下配置:
```java
public class DynamicDataSource extends AbstractRoutingDataSource {
private static final ThreadLocal<String> contextHolder = new ThreadLocal<>();
public DynamicDataSource(DataSource defaultTargetDataSource, Map<Object, Object> targetDataSources) {
super.setDefaultTargetDataSource(defaultTargetDataSource);
super.setTargetDataSources(targetDataSources);
super.afterPropertiesSet();
}
@Override
protected Object determineCurrentLookupKey() {
return contextHolder.get();
}
public static void setDataSource(String dataSource) {
contextHolder.set(dataSource);
}
public static void clearDataSource() {
contextHolder.remove();
}
}
```
6. 在需要切换数据源的地方,调用DynamicDataSource.setDataSource("dataSource1")或DynamicDataSource.setDataSource("dataSource2")方法切换数据源。
以上就是Spring Boot动态数据源配置的步骤。
阅读全文