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

1 目标

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

2 使用场景

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

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

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

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

即需要在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>

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

作者:京东物流 崔子华

来源:京东云开发者社区

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/31465.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

实例讲解,一文弄懂workqueue和waitqueue

本期主题&#xff1a; 讲清workqueue和waitqueu&#xff1a; 从中断讲起waitqueue是什么workqueue总结 往期链接&#xff1a; linux设备驱动中的并发linux设备驱动中的编译乱序和执行乱序linux设备驱动之内核模块linux字符驱动linux字符驱动之ioctl部分linux字符驱动之read、…

分布式存储Ceph的部署及应用(创建MDS、RBD、RGW 接口)

系列文章目录 文章目录 系列文章目录一、1.存储基础2. 单机存储的问题3. 分布式存储&#xff08;软件定义的存储 SDS&#xff09; 二 Ceph1.Ceph 简介2. Ceph 数据的存储过程 总结 一、 1.存储基础 1.1 单机存储设备 ●DAS&#xff08;直接附加存储&#xff0c;是直接接到计算…

SAX解析XML返回对应格式的Map对象

前言 最近有一个解析大型xml的需求&#xff0c;xml大小7M&#xff0c;其中xml结构非常复杂&#xff0c;元素各种嵌套 不乏有元素下对象&#xff0c;元素下集合&#xff0c;集合下对象&#xff0c;集合下集合&#xff0c;兄弟不同元素节点&#xff0c;元素下对象下集合&#xff…

HDFS读写流程

读数据流程 客户端向NameNode请求文件的位置&#xff1a;客户端想要访问一个文件时&#xff0c;会向NameNode发送一个请求&#xff0c;要求获取该文件在HDFS上的位置信息。 NameNode将位置信息返回给客户端&#xff1a;NameNode接收到客户端的请求后&#xff0c;会返回该文件所…

设计模式—访问者模式

需求&#xff1a;店铺采购了一批水果&#xff08;苹果及橘子&#xff09;&#xff0c;现在市场监督局来店里检查过期的水果。 public class Fruit {private String name;private Date pickDate;public Fruit(String name, Date pickDate) {this.name name;this.pickDate pic…

javaWeb之cookiesession

1 回顾 1.1 response对象 一次响应封装对象&#xff0c;由服务器创建。使用response对象将服务器需要的数据发送给浏览器。 将数据存放response对象中&#xff0c;tomcat从response对象获得数据&#xff0c;根据数据组织http响应&#xff0c;最后将http响应内容发送给浏览器&…

selenium自动化教程及使用java来爬取数据

目录 一、介绍二、下载浏览器驱动1.获取要下载的驱动版本号2.下载驱动 三、Maven如下四、简单使用五、定位器1.定位器2.说明(1) class name 定位器(2) css selector 定位器(3) id 定位器(4) name 定位器(5) link text 定位器(6) partial link text 定位器(7) tag 定位器(8) xpa…

第8讲:$.ajax方法使用详解

jQuery对象上面定义了Ajax方法&#xff08;$.ajax()&#xff09;&#xff0c;用来处理Ajax操作。调用该方法后&#xff0c;浏览器就会向服务器发出一个HTTP请求。ajax方法有很多属性&#xff0c;但并非每次调用都要使用所有属性&#xff0c;本讲详细介绍了每个属性的作用&#…

windows搭建vue开发环境

参考博客&#xff1a;最详细的vue安装教程_一只野生程序媛的博客-CSDN博客 Vue安装环境最全教程&#xff0c;傻瓜式安装_浪漫主义码农的博客-CSDN博客 1、安装nodejs&#xff0c;从下面官网下载版本&#xff0c;对应安装就行了&#xff1a; Node.js 中文网 2、安装好后&…

Linux 多路转接 —— poll

目录 传统艺能&#x1f60e;poll&#x1f923;struct pollfd&#x1f923; poll 服务器&#x1f618;PollServer类&#x1f601;运行服务器&#x1f612;事件处理&#x1f601; 服务器测试&#x1f602; 传统艺能&#x1f60e; 小编是双非本科大二菜鸟不赘述&#xff0c;欢迎米…

0基础学习地平线QAT量化感知训练

文章目录 1. 背景2. 基础理论知识3. 文件准备与程序运行4. 代码详解4.1 导入必要依赖4.2 主函数4.3 构建fx模式所需要的float_model4.4 不同阶段模型的获取4.5 定义常规模型训练与验证的函数4.6 float与qat训练代码解读——float_model/qat_model4.7 模型校准部分的代码解读——…

七、docker-compose方式运行Jenkins,更新Jenkins版本,添加npm node环境

docker-compose方式运行Jenkins&#xff0c;更新Jenkins版本&#xff0c;添加npm node环境 一、docker-compose方式安装运行Jenkins 中发现Jenkins版本有点老&#xff0c;没有node环境&#xff0c;本节来说下更新jenkins 及添加构建前端的node环境。 1. 准备好docker-compose…

三种方法将Word文档转换为PDF文件格式

如何将Word文档转换为PDF文件格式呢&#xff1f;大家在传输文件时&#xff0c;很多人喜欢使用PDF文件格式&#xff0c;因为它非常稳定&#xff0c;不会出现格式混乱的问题。但有些人可能不知道如何进行转换&#xff0c;今天我将介绍三种转换方法&#xff0c;让我们一起来学习一…

mysql 删表引出的问题

背景 将测试环境的表同步到另外一个数据库服务器中&#xff0c;但有些表里面数据巨大&#xff0c;&#xff08;其实不同步该表的数据就行&#xff0c;当时没想太多&#xff09;&#xff0c;几千万的数据&#xff01;&#xff01; 步骤 1. 既然已经把数据同步过来的话&#x…

环境配置 | Git的安装及配置[图文详情]

Git是一个开源的分布式版本控制系统&#xff0c;可以有效、高速地处理从小到大的项目版本管理。下面介绍了基础概念及详细的用图文形式介绍一下git安装过程. 目录 1.Git基础概念 2.Git的下载及安装 3.常见的git命令 Git高级技巧 Git与团队协作 1.Git基础概念 仓库&#…

认识异常

目录 异常的概念与体系结构 异常的概念 异常的体系结构 异常的分类 异常的处理 防御式编程 1. LBYL: 2. EAFP: 异常的抛出 异常的捕获 异常声明throws try-catch捕获并处理 关于异常的处理方式 finally 异常的处理流程 自定义异常类 异常的概念与体系结构 异常…

基于SpringBoot+kaptcha的验证码生成

教程 1.添加 Kaptcha 依赖 在 pom.xml 文件中添加 Kaptcha 依赖&#xff1a; <dependency><groupId>com.github.penggle</groupId><artifactId>kaptcha</artifactId><version>2.3.2</version> </dependency> <!--或者 都…

平凯星辰重磅支持 2023 开放原子全球开源峰会,开源数据库分论坛成功召开

2023 年 6 月 11 日至 13 日&#xff0c;以“开源赋能&#xff0c;普惠未来”为主题的 2023 开放原子全球开源峰会开幕式暨高峰论坛在北京成功举办。企业级开源分布式数据库厂商平凯星辰联合创始人兼 CTO 黄东旭受邀出席峰会参与开源论道圆桌&#xff0c;担任开源数据库分论坛出…

第一章 数据可视化简介(复习)

第一章 数据可视化简介 什么是可视化 定义&#xff1a;通过可视表达增强人们完成某些 任务的效率 The American Heritage Dictionary&#xff1a; The act or process of interpreting in visual terms or of putting into visible form&#xff08;用可视形式进行解释的 动作…

VUE L ∠脚手架 配置代理 ⑩⑧

目录 文章有误请指正&#xff0c;如果觉得对你有用&#xff0c;请点三连一波&#xff0c;蟹蟹支持✨ V u e j s Vuejs Vuejs初识 V u e C L I VueCLI VueCLI C L I CLI CLI V u e Vue Vue配置代理 C L I CLI CLI配置方法一 C L I CLI CLI配置方法二 C L I CLI CLI V u …