引入支持依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>3.4.0</version>
</dependency>
进行数据源配置
spring:
datasource:
dynamic:
primary: master
datasource:
master:
url:
username:
password:
driver-class-name:
slave:
url:
username:
password:
driver-class-name:
实现配置类:
DynamicDataSourceConfig
public class DynamicDataSourceConfig {
@Bean(name = "masterDataSource")
@ConfigurationProperties("spring.datasource.dynamic.datasource.master")
public DataSource masterDataSource() {
return new DruidDataSource();
}
@Bean(name = "slaveDataSource")
@ConfigurationProperties("spring.datasource.dynamic.datasource.slave")
public DataSource slaveDataSource() {
return new DruidDataSource();
}
@Bean
@Primary
public DynamicRoutingDataSource dataSource(DataSource masterDataSource, DataSource slaveDataSource) {
Map<Object, Object> targetDataSources = Maps.newHashMapWithExpectedSize(2);
targetDataSources.put("master", masterDataSource);
targetDataSources.put("slave", slaveDataSource);
return new DynamicRoutingDataSource(masterDataSource, targetDataSources);
}
}
DynamicRoutingDataSource
public class DynamicRoutingDataSource extends AbstractRoutingDataSource {
private static final ThreadLocal<String> contextHolder = new ThreadLocal<>();
public DynamicRoutingDataSource(DataSource defaultTargetDataSource, Map<Object, Object> targetDataSources) {
super.setDefaultTargetDataSource(defaultTargetDataSource);
super.setTargetDataSources(targetDataSources);
super.afterPropertiesSet();
}
@Override
protected Object determineCurrentLookupKey() {
return getDataSource();
}
public static void setDataSource(String dataSource) {
contextHolder.set(dataSource);
}
public static String getDataSource() {
return contextHolder.get();
}
public static void clearDataSource() {
contextHolder.remove();
}
}
启动了Application添加注解:
@SpringBootApplication(exclude = {
org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration.class,
DataSourceAutoConfiguration.class
})
@Import({DynamicDataSourceConfig.class})
public class TestApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(TestApplication .class, args);
}
}
实际场景使用:
public String test(){
DynamicRoutingDataSource.setDataSource("master");
Integer masterCount = testMapper.queryCount();
DynamicRoutingDataSource.setDataSource("slave");
Integer slaveCount = testMapper.queryCount();
DynamicRoutingDataSource.clearDataSource();
return null;
}