Mysql配置动态数据源
先准备多数据源的配置类
#mysql
spring.datasource.master.type = com.alibaba.druid.pool.DruidDataSource
spring.datasource.druid.master.driver-class-name = com.mysql.cj.jdbc.Driver
spring.datasource.druid.master.url=jdbc:mysql://localhost:3306/master?characterEncoding=utf8&useSSL=false&rewriteBatchedStatements=true
spring.datasource.druid.master.username = root
spring.datasource.druid.master.password = root
spring.datasource.druid.slave.driver-class-name = com.mysql.cj.jdbc.Driver
spring.datasource.druid.slave.url=jdbc:mysql://localhost:3306/slave?characterEncoding=utf8&useSSL=false&rewriteBatchedStatements=true
spring.datasource.druid.slave.username = root
spring.datasource.druid.slave.password = root
package com.chh.config;
/**
* @Author chh
* @DATE: 2024/2/23 14:33
*/
public class DatasourceConstants {
public static final String MASTER_DATA_SOURCE = "MASTER_DATA_SOURCE";
public static final String SLAVE_DATA_SOURCE = "SLAVE_DATA_SOURCE";
}
数据源的Bean类
package com.chh.config;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import javax.sql.DataSource;
/**
* @Author chh
* @DATE: 2024/2/23 11:34
*/
@Configuration
public class DataSourceConfiguration {
@Bean
@Qualifier(DatasourceConstants.MASTER_DATA_SOURCE)
@ConfigurationProperties(prefix = "spring.datasource.druid.master")
public DataSource masterDataSource() {
// 底层会自动拿到spring.datasource中的配置, 创建一个DruidDataSource
return DruidDataSourceBuilder.create().build();
}
@Bean
@Qualifier(DatasourceConstants.SLAVE_DATA_SOURCE)
@ConfigurationProperties(prefix = "spring.datasource.druid.slave")
public DataSource slaveDataSource() {
// 底层会自动拿到spring.datasource中的配置, 创建一个DruidDataSource
return DruidDataSourceBuilder.create().build();
}
@Bean
public DataSourceTransactionManager masterTransactionManager(DynamicDataSourceRouter dataSource) {
DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
dataSourceTransactionManager.setDataSource(dataSource);
return dataSourceTransactionManager;
}
@Bean
public DataSourceTransactionManager slaveTransactionManager(DynamicDataSourceRouter dataSource) {
DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
dataSourceTransactionManager.setDataSource(dataSource);
return dataSourceTransactionManager;
}
}
编写一个继承AbstractRoutingDataSource的动态数据源类
重写determineCurrentLookupKey方法和afterPropertiesSet方法
package com.chh.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.util.StringUtils;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
/**
* @Author chh
* @DATE: 2024/2/23 13:55
*/
@Configuration
@Primary
public class DynamicDataSourceRouter extends AbstractRoutingDataSource {
@Autowired
@Qualifier(DatasourceConstants.MASTER_DATA_SOURCE)
private DataSource masterDataSource;
@Autowired
@Qualifier(DatasourceConstants.SLAVE_DATA_SOURCE)
private DataSource slaveDataSource;
public static ThreadLocal<String> dataSourceName = new ThreadLocal<>();
@Override
protected Object determineCurrentLookupKey() {
String datasource = dataSourceName.get();
System.out.println(datasource);
System.out.println("======================切换数据源为:" + datasource);
return StringUtils.isEmpty(datasource) ? DatasourceConstants.MASTER_DATA_SOURCE : datasource;
}
@Override
public void afterPropertiesSet() {
Map<Object, Object> targetDataSources = new HashMap<>(2);
targetDataSources.put(DatasourceConstants.MASTER_DATA_SOURCE, masterDataSource);
targetDataSources.put(DatasourceConstants.SLAVE_DATA_SOURCE, slaveDataSource);
super.setDefaultTargetDataSource(masterDataSource);
super.setTargetDataSources(targetDataSources);
System.out.println("======================初始化数据源======================");
super.afterPropertiesSet();
}
}
创建一个注解用注解实现动态控制数据源
package com.chh.config;
import java.lang.annotation.*;
/**
* @Author chh
* @DATE: 2024/2/23 14:38
*/
@Documented
@Target({ElementType.METHOD,ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface DS {
String value() default DatasourceConstants.MASTER_DATA_SOURCE;
}
编写一个切面类在执行方法前切换到合适的数据源
package com.chh.config;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
/**
* @Author chh
* @DATE: 2024/2/23 14:10
*/
@Component
@Aspect
public class DynamicDataSourceAspect implements Ordered {
// 前置
@Before("within(com.chh.service.impl.*) && @annotation(ds)")
public void before(JoinPoint point, DS ds) {
String name = ds.value();
DynamicDataSourceRouter.dataSourceName.set(name);
System.out.println("======================切面通知切换到数据源:" + name);
}
@Override
public int getOrder() {
return 0;
}
}
自行编写测试代码即可