Spring AbstractRoutingDataSource 源码分析

** 本文基于Spring 4.1.6 RELEASE源码 **


先看看之前咱们在spring-mybatis.xml文件中配置的动态数据源,如下:

<bean id="dataSource" class="com.ricky.codelab.spring.ds.DynamicRoutingDataSource">
    <property name="targetDataSources">
        <map key-type="com.ricky.codelab.spring.ds.RouteStrategy">
            <entry key="slave1" value-ref="slave1DataSource"/>
            <entry key="slave2" value-ref="slave2DataSource"/>
        </map>
    </property>
    <!-- 默认目标数据源为主库数据源 -->
    <property name="defaultTargetDataSource" ref="masterDataSource"/>
</bean>

DynamicRoutingDataSource 继承自org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource类,代码如下:

package com.ricky.codelab.spring.ds;

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

/**
 * 动态数据源切换
 *
 * @author Ricky Fung
 * @create 2016-10-18 22:41
 */
public class DynamicRoutingDataSource extends AbstractRoutingDataSource {

    @Override
    protected Object determineCurrentLookupKey() {

        return DynamicRoutingContextHolder.getRouteStrategy();
    }
}

AbstractRoutingDataSource 类的定义,源码如下:

package org.springframework.jdbc.datasource.lookup;

public abstract class AbstractRoutingDataSource extends AbstractDataSource implements InitializingBean {
    private Map<Object, Object> targetDataSources;
    private Object defaultTargetDataSource;
    private boolean lenientFallback = true;
    private DataSourceLookup dataSourceLookup = new JndiDataSourceLookup();
    private Map<Object, DataSource> resolvedDataSources;
    private DataSource resolvedDefaultDataSource;
}

AbstractRoutingDataSource 实现了InitializingBean接口,Spring容器启动时会回调其afterPropertiesSet()方法,AbstractRoutingDataSource afterPropertiesSet()如下:

public void afterPropertiesSet() {
    if(this.targetDataSources == null) {
        throw new IllegalArgumentException("Property \'targetDataSources\' is required");
    } else {
        this.resolvedDataSources = new HashMap(this.targetDataSources.size());
        Iterator var1 = this.targetDataSources.entrySet().iterator();

        while(var1.hasNext()) {
            Entry entry = (Entry)var1.next();
            Object lookupKey = this.resolveSpecifiedLookupKey(entry.getKey());
            DataSource dataSource = this.resolveSpecifiedDataSource(entry.getValue());
            this.resolvedDataSources.put(lookupKey, dataSource);
        }

        if(this.defaultTargetDataSource != null) {
            this.resolvedDefaultDataSource = this.resolveSpecifiedDataSource(this.defaultTargetDataSource);
        }

    }
}

protected DataSource resolveSpecifiedDataSource(Object dataSource) throws IllegalArgumentException {
    if(dataSource instanceof DataSource) {
        return (DataSource)dataSource;
    } else if(dataSource instanceof String) {
        return this.dataSourceLookup.getDataSource((String)dataSource);
    } else {
        throw new IllegalArgumentException("Illegal data source value - only [javax.sql.DataSource] and String supported: " + dataSource);
    }
}

这里主要把在xml中配置的targetDataSources解析到resolvedDataSources,defaultTargetDataSource 赋值到resolvedDefaultDataSource 。

另外,AbstractRoutingDataSource 继承自AbstractDataSource,而AbstractDataSource 是DataSource的一个子类,如下:

package org.springframework.jdbc.datasource;

public abstract class AbstractDataSource implements DataSource {
    protected final Log logger = LogFactory.getLog(this.getClass());

    public AbstractDataSource() {
    }
}

因此,我们只需要看AbstractRoutingDataSource 的getConnection()方法实现即可,如下:

public Connection getConnection() throws SQLException {
    return this.determineTargetDataSource().getConnection();
}

public Connection getConnection(String username, String password) throws SQLException {
    return this.determineTargetDataSource().getConnection(username, password);
}

determineTargetDataSource()方法如下:


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;
    }
}

determineTargetDataSource方法决定返回哪个DataSource 对象,它根据determineCurrentLookupKey方法(这个方法正是我们在DynamicRoutingDataSource类中重写的方法)获取数据源的key,然后从 resolvedDataSources中根据key取出DataSource ,如果返回的DataSource 为空,则使用默认的DataSource。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,993评论 6 342
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,123评论 19 139
  • application的配置属性。 这些属性是否生效取决于对应的组件是否声明为Spring应用程序上下文里的Bea...
    新签名阅读 5,446评论 1 27
  • 暮色赶走了温暖的阳光,霸占了天地。烟灰色的云朵一块一块地弥散开来抢占了明亮的天空。又是一日要过去了。虽是舍不得,却...
    菡萏琪玲阅读 572评论 0 0
  • 不合适的人,分开该庆幸,因为终于不再互相折磨了。 从这种意义上来讲,没跟那个最喜欢的人走到婚姻这一步,是一种幸运,...
    云朵上的喵阅读 1,442评论 0 3