Spring 动态数据源路由-源码分析

扫码关注公众号:Java 技术驿站

发送:vip
将链接复制到本浏览器,永久解锁本站全部文章

【公众号:Java 技术驿站】 【加作者微信交流技术,拉技术群】
免费领取 2000+ 道 Java 面试题

本文基于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 继承自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。


来源:http://ddrv.cn/a/88268

赞(0) 打赏
版权归原创作者所有,任何形式的转载请联系博主:daming_90:Java 技术驿站 » Spring 动态数据源路由-源码分析

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏