Spring中实现动态数据源切换,基于AbstractRoutingDataSource

背景

在项目开发过程中,我们可能会遇到一个场景:某个类型数据源有多个数据源实例,需要我们按照不同的请求切换到不同数据源去。

而目前绝大多数java应用都是基于Spring框架来开发,我们很多时候相关的数据源连接都是交给了Spring框架去管理,这就需要Spring能够支持动态数据源切换。

方案

Spring中预留了这个接口,通过AbstractRoutingDataSource能够动态切换数据源。

java 复制代码
public abstract class AbstractRoutingDataSource extends AbstractDataSource implements InitializingBean {

这是一个抽象类,预留了一个抽象方法:

java 复制代码
protected abstract Object determineCurrentLookupKey();

我们知道,数据源一般都会提供一个getConnection方法来获取一个连接,在AbstractRoutingDataSource 实现如下:

java 复制代码
	@Override
	public Connection getConnection() throws SQLException {
		return determineTargetDataSource().getConnection();
	}
	protected DataSource determineTargetDataSource() {
		Assert.notNull(this.resolvedDataSources, "DataSource router not initialized");
		Object lookupKey = determineCurrentLookupKey();
		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 + "]");
		}
		return dataSource;
	}

可以看到,AbstractRoutingDataSource 获取连接的主要逻辑就是通过determineCurrentLookupKey获取到一个数据源的关联key,然后从resolvedDataSources中去获取。

resolvedDataSources的初始化,则放在afterPropertiesSet中:

java 复制代码
	@Override
	public void afterPropertiesSet() {
		if (this.targetDataSources == null) {
			throw new IllegalArgumentException("Property 'targetDataSources' is required");
		}
		this.resolvedDataSources = CollectionUtils.newHashMap(this.targetDataSources.size());
		this.targetDataSources.forEach((key, value) -> {
			Object lookupKey = resolveSpecifiedLookupKey(key);
			DataSource dataSource = resolveSpecifiedDataSource(value);
			this.resolvedDataSources.put(lookupKey, dataSource);
		});
		if (this.defaultTargetDataSource != null) {
			this.resolvedDefaultDataSource = resolveSpecifiedDataSource(this.defaultTargetDataSource);
		}
	}

这里起始就是通过targetDataSources中指定的数据源复制到resolvedDataSources 中去。因此如果多数源是固定的,那么只需要实现determineCurrentLookupKey方法即可。但是如果多数据源不固定,比如可能会有数据源的变更,那么这种实现是不能够支持,因为这种实现从服务启动的视乎,后续数据源就不能发生变更,这需要我们自己实现determineTargetDataSource.

下面是一个参考实现:

java 复制代码
public class DataSourceContextHolder {

    private static final ThreadLocal<String> DATASOURCE_CONTEXT_KEY_HOLDER = new ThreadLocal<>();


    public static void switchDataSource(String key){
        log.info("Switch to data source:" + key);
        DATASOURCE_CONTEXT_KEY_HOLDER.set(key);
    }
    public static String getDataSourceKey(){
        return DATASOURCE_CONTEXT_KEY_HOLDER.get() ;
    }

}

public class DynamicDataSource extends AbstractRoutingDataSource {

    private Map<Object, Object> targetDataSources = new HashMap<>();
    private Map<Object, DataSource> dataSources = new HashMap<>();
    public DynamicDataSource (){
        super.setDefaultTargetDataSource(null);
        super.setTargetDataSources(targetDataSources);
        super.afterPropertiesSet();
    }
 @Override
    protected DataSource determineTargetDataSource() {
        Object dataSourceKey = determineCurrentLookupKey();
        return dataSources.get(dataSourceKey);
    }
    @Override
    protected Object determineCurrentLookupKey() {
        return DataSourceContextHolder .getDataSourceKey();
    }
    public synchronized void addDataSource(String key, DataSource dataSource){
        targetDataSources.put(key,dataSource);
        dataSources.put(key,dataSource);
        log.info("add tenant dynamic dataSource for tenantId = {} ",key);
    }
}

这样我们通过DataSourceContextHolder 来调整当前线程关联的数据源。

相关推荐
m0_748554815 小时前
golang如何实现用户订阅偏好管理_golang用户订阅偏好管理实现总结
jvm·数据库·python
lee_curry5 小时前
第四章 jvm中的垃圾回收器
java·jvm·垃圾收集器
早日退休!!!6 小时前
《数据结构选型指南》笔记
数据结构·数据库·oracle
xcLeigh7 小时前
KES数据库性能优化实战
数据库·sql·性能优化·sql优化·数据性能
阿正呀7 小时前
Redis怎样实现本地缓存的高效失效通知
jvm·数据库·python
yoyo_zzm7 小时前
Laravel9.x新特性全解析
数据库·mysql·nginx
九转成圣7 小时前
Java 性能优化实战:如何将海量扁平数据高效转化为类目字典树?
java·开发语言·json
2501_901200537 小时前
mysql如何设置InnoDB引擎参数_优化innodb_buffer_pool
jvm·数据库·python
直奔標竿7 小时前
Java开发者AI转型第二十七课!Spring AI 个人知识库实战(六)——全栈闭环收官,解锁前端流式渲染终极技巧
java·开发语言·前端·人工智能·后端·spring
金銀銅鐵8 小时前
[java] 编译之后的记录类(Record Classes)长什么样子(上)
java·jvm·后端