spring-jdbc之AbstractRoutingDataSource源码解析

翻看之前springboot集成的mybatis读写分离,发现还有些疏漏 ,有的还不甚理解,于是翻看下源码;

读写分离 主要就是数据路由的时候重写roundRobinDataSouceProxy方法 ,roundRobinDataSouceProxy中最重要的是 AbstractRoutingDataSource类中的一个抽象方法determineCurrentLookupKey()

下面我们来看下AbstractRoutingDataSource类

 /**
     * 把所有数据库都放在路由中
     * @return
     */
    @Bean(name="roundRobinDataSouceProxy")
    public AbstractRoutingDataSource roundRobinDataSouceProxy() {

        Map<Object, Object> targetDataSources = new HashMap<Object, Object>();
        //把所有数据库都放在targetDataSources中,注意key值要和determineCurrentLookupKey()中代码写的一至,
        //否则切换数据源时找不到正确的数据源
        targetDataSources.put(DataSourceType.write.getType(), writeDataSource);
        targetDataSources.put(DataSourceType.read.getType(), readDataSource);
 
 
        //路由类,寻找对应的数据源
        AbstractRoutingDataSource proxy = new AbstractRoutingDataSource(){
            
            @Override
            protected Object determineCurrentLookupKey() {
                
                return null;
            }
        };
	
        proxy.setDefaultTargetDataSource(writeDataSource);//默认库
	设置数据源映射
        proxy.setTargetDataSources(targetDataSources);
        return proxy;
    }

AbstractRoutingDataSource源码
 

public abstract class AbstractRoutingDataSource extends AbstractDataSource implements InitializingBean{
  public Connection getConnection() throws SQLException {
        return this.determineTargetDataSource().getConnection();
    }
 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;
        }
    }

        protected abstract Object determineCurrentLookupKey();

AbstractRoutingDataSource源码中有个Object lookupKey = this.determineCurrentLookupKey();

在spring源码中很常见的引用 抽象类中的方法引用抽象方法的实现;

最核心的就determineCurrentLookupKey方法实现, 返回一个datasource实例枚举key,然后当前resolvedDataSources中获取key对应的数据源,从而完成,数据源的动态切换。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值