一种实现Spring动态数据源切换的方法 | 京东云技术团队

京东云开发者
• 阅读 256

1 目标

不在现有查询代码逻辑上做任何改动,实现dao维度的数据源切换(即表维度)

2 使用场景

节约bdp的集群资源。接入新的宽表时,通常uat验证后就会停止集群释放资源,在对应的查询服务器uat环境时需要查询的是生产库的表数据(uat库表因为bdp实时任务停止,没有数据落入),只进行服务器配置文件的改动而无需进行代码的修改变更,即可按需切换查询的数据源。

2.1 实时任务对应的集群资源

一种实现Spring动态数据源切换的方法 | 京东云技术团队)

2.2 实时任务产生的数据进行存储的两套环境

一种实现Spring动态数据源切换的方法 | 京东云技术团队)

2.3 数据使用系统的两套环境(查询展示数据)

一种实现Spring动态数据源切换的方法 | 京东云技术团队)

即需要在zhongyouex-bigdata-uat中查询生产库的数据。

3 实现过程

3.1 实现重点

  1. org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource
    spring提供的这个类是本次实现的核心,能够让我们实现运行时多数据源的动态切换,但是数据源是需要事先配置好的,无法动态的增加数据源。
  2. Spring提供的Aop拦截执行的mapper,进行切换判断并进行切换。

注:另外还有一个就是ThreadLocal类,用于保存每个线程正在使用的数据源。

3.2 AbstractRoutingDataSource解析

public abstract class AbstractRoutingDataSource extends AbstractDataSource 
implements InitializingBean{
    @Nullable
    private Map<Object, Object> targetDataSources;

    @Nullable
    private Object defaultTargetDataSource;

    @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;
    }
    @Override
    public void afterPropertiesSet() {
        if (this.targetDataSources == null) {
            throw new IllegalArgumentException("Property 'targetDataSources' is required");
        }
        this.resolvedDataSources = new HashMap<>(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);
        }
    }

从上面源码可以看出它继承了AbstractDataSource,而AbstractDataSource是javax.sql.DataSource的实现类,拥有getConnection()方法。获取连接的getConnection()方法中,重点是determineTargetDataSource()方法,它的返回值就是你所要用的数据源dataSource的key值,有了这个key值,resolvedDataSource(这是个map,由配置文件中设置好后存入targetDataSources的,通过targetDataSources遍历存入该map)就从中取出对应的DataSource,如果找不到,就用配置默认的数据源。

看完源码,我们可以知道,只要扩展AbstractRoutingDataSource类,并重写其中的determineCurrentLookupKey()方法返回自己想要的key值,就可以实现指定数据源的切换!

3.3 运行流程

  1. 我们自己写的Aop拦截Mapper
  2. 判断当前执行的sql所属的命名空间,然后使用命名空间作为key读取系统配置文件获取当前mapper是否需要切换数据源
  3. 线程再从全局静态的HashMap中取出当前要用的数据源
  4. 返回对应数据源的connection去做相应的数据库操作

3.4 不切换数据源时的正常配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

<!-- clickhouse数据源   -->
    <bean id="dataSourceClickhousePinpin" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close" lazy-init="true">
        <property name="url" value="${clickhouse.jdbc.pinpin.url}" />
    </bean>

    <bean id="singleSessionFactoryPinpin" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- ref直接指向 数据源dataSourceClickhousePinpin  -->
<property name="dataSource" ref="dataSourceClickhousePinpin" />
    </bean>

</beans>

3.5 进行动态数据源切换时的配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- clickhouse数据源 1  -->
    <bean id="dataSourceClickhousePinpin" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close" lazy-init="true">
        <property name="url" value="${clickhouse.jdbc.pinpin.url}" />
    </bean>
<!-- clickhouse数据源 2  -->
    <bean id="dataSourceClickhouseOtherPinpin" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close" lazy-init="true">
        <property name="url" value="${clickhouse.jdbc.other.url}" />
    </bean>
 <!-- 新增配置 封装注册的两个数据源到multiDataSourcePinpin里 -->
 <!-- 对应的key分别是 defaultTargetDataSource和targetDataSources-->
    <bean id="multiDataSourcePinpin" class="com.zhongyouex.bigdata.common.aop.MultiDataSource">
      <!-- 默认使用的数据源-->
<property name="defaultTargetDataSource" ref="dataSourceClickhousePinpin"></property>
        <!-- 存储其他数据源,对应源码中的targetDataSources -->
<property name="targetDataSources">
            <!-- 该map即为源码中的resolvedDataSources-->
            <map>
                <!-- dataSourceClickhouseOther 即为要切换的数据源对应的key -->
<entry key="dataSourceClickhouseOther" value-ref="dataSourceClickhouseOtherPinpin"></entry>
            </map>
        </property>
    </bean>

    <bean id="singleSessionFactoryPinpin" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- ref指向封装后的数据源multiDataSourcePinpin  -->
<property name="dataSource" ref="multiDataSourcePinpin" />
    </bean>
</beans>

核心是AbstractRoutingDataSource,由spring提供,用来动态切换数据源。我们需要继承它,来进行操作。这里我们自定义的com.zhongyouex.bigdata.common.aop.MultiDataSource就是继承了AbstractRoutingDataSource

package com.zhongyouex.bigdata.common.aop;

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
/**
 * @author: cuizihua
 * @description: 动态数据源
 * @date: 2021/9/7 20:24
 * @return
 */
public class MultiDataSource extends AbstractRoutingDataSource {

    /* 存储数据源的key值,InheritableThreadLocal用来保证父子线程都能拿到值。
     */
    private static final ThreadLocal<String> dataSourceKey = new InheritableThreadLocal<String>();

    /**
     * 设置dataSourceKey的值
     *
     * @param dataSource
     */
    public static void setDataSourceKey(String dataSource) {
        dataSourceKey.set(dataSource);
    }

    /**
     * 清除dataSourceKey的值
     */
    public static void toDefault() {
        dataSourceKey.remove();
    }

    /**
     * 返回当前dataSourceKey的值
     */
    @Override
    protected Object determineCurrentLookupKey() {
        return dataSourceKey.get();
    }
}

3.6 AOP代码

package com.zhongyouex.bigdata.common.aop;
import com.zhongyouex.bigdata.common.util.LoadUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import java.lang.reflect.Method;

/**
 * 方法拦截  粒度在mapper上(对应的sql所属xml)
 * @author cuizihua
 * @desc 切换数据源
 * @create 2021-09-03 16:29
 **/
@Slf4j
public class MultiDataSourceInterceptor {
//动态数据源对应的key
    private final String otherDataSource = "dataSourceClickhouseOther";

    public void beforeOpt(JoinPoint mi) {
//默认使用默认数据源
        MultiDataSource.toDefault();
        //获取执行该方法的信息
        MethodSignature signature = (MethodSignature) mi.getSignature();
        Method method = signature.getMethod();
        String namespace = method.getDeclaringClass().getName();
//本项目命名空间统一的规范为xxx.xxx.xxxMapper
        namespace = namespace.substring(namespace.lastIndexOf(".") + 1);
//这里在配置文件配置的属性为xxxMapper.ck.switch=1 or 0  1表示切换
        String isOtherDataSource = LoadUtil.loadByKey(namespace, "ck.switch");
        if ("1".equalsIgnoreCase(isOtherDataSource)) {
            MultiDataSource.setDataSourceKey(otherDataSource);
            String methodName = method.getName();
        }
    }
}

3.7 AOP代码逻辑说明

通过org.aspectj.lang.reflect.MethodSignature可以获取对应执行sql的xml空间名称,拿到sql对应的xml命名空间就可以获取配置文件中配置的属性决定该xml是否开启切换数据源了。

3.8 对应的aop配置

<!--动态数据源-->
<bean id="multiDataSourceInterceptor" class="com.zhongyouex.bigdata.common.aop.MultiDataSourceInterceptor" ></bean>
<!--将自定义拦截器注入到spring中-->
<aop:config proxy-target-class="true" expose-proxy="true">
    <aop:aspect ref="multiDataSourceInterceptor">
        <!--切入点,也就是你要监控哪些类下的方法,这里写的是DAO层的目录,表达式需要保证只扫描dao层-->
        <aop:pointcut id="multiDataSourcePointcut" expression="execution(*  com.zhongyouex.bigdata.clickhouse..*.*(..)) "/>
        <!--在该切入点使用自定义拦截器-->
        <aop:before method="beforeOpt" pointcut-ref="multiDataSourcePointcut" />
    </aop:aspect>
</aop:config>

以上就是整个实现过程,希望能帮上有需要的小伙伴

作者:京东物流 崔子华

来源:京东云开发者社区

点赞
收藏
评论区
推荐文章
Wesley13 Wesley13
2年前
java 微服务分布式 springcloud vue.js flowable 流程引擎
1.代码生成器:\正反双向\(单表、主表、明细表、树形表,快速开发利器)freemaker模版技术,0个代码不用写,生成完整的一个模块,带页面、建表sql脚本、处理类、service等完整模块2.多数据源:(支持同时连接无数个数据库,可以不同的模块连接不同数的据库)支持N个数据源3.阿里数据库连接池dru
Easter79 Easter79
2年前
sql注入
反引号是个比较特别的字符,下面记录下怎么利用0x00SQL注入反引号可利用在分隔符及注释作用,不过使用范围只于表名、数据库名、字段名、起别名这些场景,下面具体说下1)表名payload:select\from\users\whereuser\_id1limit0,1;!(https://o
Stella981 Stella981
2年前
GreenPlum tidb 性能比较
主要的需求  针对大体量表的OLAP统计查询,需要找到一个稳定,高性能的大数据数据库,具体使用  数据可以实时的写入和查询,并发的tps不是很高建立数据仓库,模式上主要采用星星模型、雪花模型,或者宽表前端展示分为3类 saiku、granafa、c代码开发数据体量:事实表在35亿、维度表大的在500
Stella981 Stella981
2年前
Kerberos无约束委派的攻击和防御
 0x00前言简介当ActiveDirectory首次与Windows2000Server一起发布时,Microsoft就提供了一种简单的机制来支持用户通过Kerberos对Web服务器进行身份验证并需要授权用户更新后端数据库服务器上的记录的方案。这通常被称为Kerberosdoublehopissue(双跃点问题),
Wesley13 Wesley13
2年前
oracle查询表数据并重新插入到本表
oracle查询表数据并重新插入到本表CreateTime2018年5月17日10:30:10Author:Marydon1.情景描述查询表中数据SELECTFROMat_aut
Wesley13 Wesley13
2年前
PHP二维数据排序,二维数据模糊查询
一、因为项目中的一个报表需要合并三个表的数据,所以分表查询再合并数据,利用PHP数组函数进行排序,搜索。三表合并后的数组结构如下:Array(0Array(history_id12sla_group_
Wesley13 Wesley13
2年前
ThinkPHP 根据关联数据查询 hasWhere 的使用实例
很多时候,模型关联后需要根据关联的模型做查询。场景:广告表(ad),广告类型表(ad\_type),现在需要筛选出广告类型表中id字段为1且广告表中status为1的列表先看关联的设置部分 publicfunctionadType(){return$thisbelongsTo('A
Stella981 Stella981
2年前
Hibernate纯sql查询结果和该sql在数据库直接查询结果不一致
问题:今天在做一个查询的时候发现一个问题,我先在数据库实现了我需要的sql,然后我在代码中代码:selectdistinctd.id,d.name,COALESCE(c.count_num,0),COALESCE(c.count_fix,0),COALESCE(c
Wesley13 Wesley13
2年前
mysql出现Waiting for table metadata lock的解决方法
查询某一个表时,一直没有显示数据,于是就showprocesslist;!(https://oscimg.oschina.net/oscnet/07f86cfca979bba85837f1b6352eb00ec33.jpg)发现有表已经被锁了,关掉了之前的查询语句可以看到!(https://oscimg.oschina.net/oscn
京东云开发者 京东云开发者
6个月前
Mybatis 拦截器实现单数据源内多数据库切换 | 京东物流技术团队
物流的分拣业务在某些分拣场地只有一个数据源,因为数据量比较大,将所有数据存在一张表内查询速度慢,也为了做不同设备数据的分库管理,便在这个数据源内创建了多个不同库名但表完全相同的数据库,如下图所示:现在需要上线报表服务来查询所有数据库中的数据进行统计,那么现