本文主要内容
1. 动态数据源实现目标;
2. AbstractRoutingDataSource类分析
3. SpringBoot整合MyBatis动态数据源实现
项目中存在多个数据源连接,根据不同接口,动态连接不同的数据源DataSources对象,根据不同的业务逻辑操作不同数据源
1. AbstractRoutingDataSource是由Spring提供的标准数据源
public abstract class AbstractRoutingDataSource extends AbstractDataSource implements InitializingBean {
public abstract class AbstractDataSource implements DataSource {
2. AbstractRoutingDataSource 类中,配置了多个数据源的Map集合,根据不同的key,取出不同的DataSource ,在获取目标数据源时,调用了this.determineCurrentLookupKey(); 获取key,从而拿到对应的DataSource;因此可以实现 determineCurrentLookupKey 方法,操作key,从而动态切换数据源DataSource对象
public abstract class AbstractRoutingDataSource extends AbstractDataSource implements InitializingBean {
@Nullable
private Map
@Nullable
private Object defaultTargetDataSource;
private boolean lenientFallback = true;
private DataSourceLookup dataSourceLookup = new JndiDataSourceLookup();
@Nullable
private Map
@Nullable
private DataSource resolvedDefaultDataSource;.....
protected DataSource determineTargetDataSource() {
Assert.notNull(this.resolvedDataSources, "DataSource router not initialized");
Object lookupKey = this.determineCurrentLookupKey();
DataSource dataSource = (DataSource)this.resolvedDataSources.get(lookupKey);
if (dataSource == null && (this.lenientFallback || lookupKey == null)) {
dataSource = this.resolvedDefaultDataSource;
}if (dataSource == null) {
throw new IllegalStateException("Cannot determine target DataSource for lookup key [" + lookupKey + "]");
} else {
return dataSource;
}
}@Nullable
protected abstract Object determineCurrentLookupKey();
}
1. 配置多数据源信息
spring.datasource.slave.jdbc-url=jdbc:mysql://localhost:3306/test_mybatis_slave?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC spring.datasource.slave.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.slave.username=root spring.datasource.slave.password=123456 spring.datasource.master.jdbc-url=jdbc:mysql://localhost:3306/test_mybatis_master?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC spring.datasource.master.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.master.username=root spring.datasource.master.password=123456
2. 定义RoutingDataSourceContext类,绑定线程用于多数据源datasource集合Map的key值生成及取值(基于 ThreadLocal 为基础,存放 key,获取key,移除key)
public class RoutingDataSourceContext { static final ThreadLocalthreadLocal = new ThreadLocal<>(); public RoutingDataSourceContext(String key){ threadLocal.set(key); } static String getRoutingDataSourceKey(){ String key = threadLocal.get(); return key == null ? "master" : key; } }
3.自定义RoutingDataSource 继承 AbstractRoutingDataSource,重写 数据请求之前定义key值方法determineCurrentLookupKey
public class RoutingDataSource extends AbstractRoutingDataSource { @Override protected Object determineCurrentLookupKey() { return RoutingDataSourceContext.getRoutingDataSourceKey(); } }
4. 增加数据源配置类DynDataSourceConfiguration,用于创建 多数据源对象(数据源连接中的master,slave)及主数据源(RoutingDataSource)
@Configuration public class DynDataSourceConfiguration { @Bean @ConfigurationProperties(prefix = "spring.datasource.slave") public DataSource slaveDataSource(){ return DataSourceBuilder.create().build(); } @Bean @ConfigurationProperties(prefix = "spring.datasource.master") public DataSource masterDataSource(){ return DataSourceBuilder.create().build(); } @Bean @Primary public DataSource routingDataSource( @Autowired @Qualifier("slaveDataSource") DataSource slaveDataSource, @Autowired @Qualifier("masterDataSource") DataSource masterDataSource ){ RoutingDataSource routingDataSource = new RoutingDataSource(); // 封装数据源 map Map
5. 自定义注解类 RoutingWith用于指定方法中数据源
@Target(ElementType.METHOD) @Documented @Retention(RetentionPolicy.RUNTIME) public @interface RoutingWith { String value(); }
6.通过spring中AOP机制,实现方法调用前设置数据源key
引入aop 功能jar
org.springframework.boot spring-boot-starter-aop
定义RoutingAspect类,针对使用了@RoutingWith注解的方法进行增强
@Component @Aspect public class RoutingAspect { // AOP增强用于动态获取数据源 针对使用了 自定义的注解 RoutingWith 的方法 名字同参数中的 routingWith @Around("@annotation(routingWith)") public Object routingWithDataSource(ProceedingJoinPoint proceedingJoinPoint, RoutingWith routingWith) throws Throwable { RoutingDataSourceContext routingDataSourceContext = new RoutingDataSourceContext(routingWith.value()); return proceedingJoinPoint.proceed(); } }
7. 需要指定数据源的方法,配置@ RoutingWith注解,指定数据源
@RoutingWith("master") public ListfindAllMaster() { return userMapper.findAll(); } @RoutingWith("slave") public List findAllSlave() { return userMapper.findAll(); }