展开菜单
首页 精品内容 本月促销 装机必备 Windows PDF教程 macOS软件 IOS软件 Android AI 专题
全部分类

当前位置:

首页 > 编程开发 > SpringBoot基于AbstractRoutingDataSource如何实现多数据源动态切换

SpringBoot基于AbstractRoutingDataSource如何实现多数据源动态切换

一、场景在生产业务中,有一些任务执行了耗时较长的查询操作,在实时性要求不高的时候,我们希望将这些查询sql分离出来,去从库查询,以减少应用对主数据库的压力。一种方案是在配置文件中配置多个数据源,然后通过配置类来获取数据源以及mapper相关的扫描配置,不同的数据源配置不佟的mapper扫描位置,然后需要哪一个数据源就注入哪一个mapper接口即可,这种方法比较简单。特征是通过mapper扫描位置区分数据源。第二种方案是配置一个默认使用的数据源,然后定义多个其他的数据源,使用aop形成注解式选择数据源。此种

本文目录

    一、场景

    在生产业务中,有一些任务执行了耗时较长的查询操作,在实时性要求不高的时候,我们希望将这些查询sql分离出来,去从库查询,以减少应用对主数据库的压力。

    一种方案是在配置文件中配置多个数据源,然后通过配置类来获取数据源以及mapper相关的扫描配置,不同的数据源配置不佟的mapper扫描位置,然后需要哪一个数据源就注入哪一个mapper接口即可,这种方法比较简单。特征是通过mapper扫描位置区分数据源。

    第二种方案是配置一个默认使用的数据源,然后定义多个其他的数据源,使用aop形成注解式选择数据源。此种方案实现的核心是对AbstractRoutingDataSource 类的继承。这是本文的重点。

    二、原理

    AbstractRoutingDataSource的多数据源动态切换的核心逻辑是:在程序运行时,把数据源数据源通过 AbstractRoutingDataSource 动态织入到程序中,灵活的进行数据源切换。
    基于AbstractRoutingDataSource的多数据源动态切换,可以实现读写分离。逻辑如下:

    /**
         * Retrieve the current target DataSource. Determines the
         * {@link #determineCurrentLookupKey() current lookup key}, performs
         * a lookup in the {@link #setTargetDataSources targetDataSources} map,
         * falls back to the specified
         * {@link #setDefaultTargetDataSource default target DataSource} if necessary.
         * @see #determineCurrentLookupKey()
         */
        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;
        }
    /**
         * Determine the current lookup key. This will typically be
         * implemented to check a thread-bound transaction context.
         * 

    Allows for arbitrary keys. The returned key needs      * to match the stored lookup key type, as resolved by the      * {@link #resolveSpecifiedLookupKey} method.      */     @Nullable     protected abstract Object determineCurrentLookupKey();

    通过实现抽象方法determineCurrentLookupKey指定需要切换的数据源

    三、代码示例

    示例中主要依赖 

    com.alibaba.druid;tk.mybatis

    定义一个类用于关联数据源。通过 TheadLocal 来保存每个线程选择哪个数据源的标志(key)

    @Slf4j
    public class DynamicDataSourceContextHolder {
     
     
        private static final ThreadLocal contextHolder = new ThreadLocal();
        public static List dataSourceIds = new ArrayList();
     
        public static void setDataSourceType(String dataSourceType) {
            log.info("设置当前数据源为{}",dataSourceType);
            contextHolder.set(dataSourceType);
        }
     
        public static String getDataSourceType() {
            return contextHolder.get() ;
        }
     
        public static void clearDataSourceType() {
            contextHolder.remove();
        }
     
        public static boolean containsDataSource(String dataSourceId){
            log.info("list = {},dataId={}", JSON.toJSON(dataSourceIds),dataSourceId);
            return dataSourceIds.contains(dataSourceId);
        }
    }

    继承

    AbstractRoutingDataSource

    public class DynamicDataSource  extends AbstractRoutingDataSource {
     
        @Override
        protected Object determineCurrentLookupKey() {
     
            return  DynamicDataSourceContextHolder.getDataSourceType();
        }
    }

    配置主数据库master 与从数据库slave(略)。数据源配置可以从简

    @Configuration
    @tk.mybatis.spring.annotation.MapperScan(value = {"com.server.dal.dao"})
    @ConditionalOnProperty(name = "java.druid.datasource.master.url")
    public class JavaDruidDataSourceConfiguration {
     
        private static final Logger logger = LoggerFactory.getLogger(JavaDruidDataSourceConfiguration.class);
     
        @Resource
        private JavaDruidDataSourceProperties druidDataSourceProperties;
        @Primary
        @Bean(name = "masterDataSource", initMethod = "init", destroyMethod = "close")
        @ConditionalOnMissingBean(name = "masterDataSource")
        public DruidDataSource javaReadDruidDataSource() {
     
            DruidDataSource result = new DruidDataSource();
     
            try {
    //            result.setName(druidDataSourceProperties.getName());
                result.setUrl(druidDataSourceProperties.getUrl());
                result.setUsername(druidDataSourceProperties.getUsername());
                result.setPassword(druidDataSourceProperties.getPassword());
                result.setConnectionProperties(
                        "config.decrypt=false;config.decrypt.key=" + druidDataSourceProperties.getPwdPublicKey());
                result.setFilters("config");
                result.setMaxActive(druidDataSourceProperties.getMaxActive());
                result.setInitialSize(druidDataSourceProperties.getInitialSize());
                result.setMaxWait(druidDataSourceProperties.getMaxWait());
                result.setMinIdle(druidDataSourceProperties.getMinIdle());
                result.setTimeBetweenEvictionRunsMillis(druidDataSourceProperties.getTimeBetweenEvictionRunsMillis());
                result.setMinEvictableIdleTimeMillis(druidDataSourceProperties.getMinEvictableIdleTimeMillis());
                result.setValidationQuery(druidDataSourceProperties.getValidationQuery());
                result.setTestWhileIdle(druidDataSourceProperties.isTestWhileIdle());
                result.setTestOnBorrow(druidDataSourceProperties.isTestOnBorrow());
                result.setTestOnReturn(druidDataSourceProperties.isTestOnReturn());
                result.setPoolPreparedStatements(druidDataSourceProperties.isPoolPreparedStatements());
                result.setMaxOpenPreparedStatements(druidDataSourceProperties.getMaxOpenPreparedStatements());
     
                if (druidDataSourceProperties.isEnableMonitor()) {
                    StatFilter filter = new StatFilter();
                    filter.setLogSlowSql(druidDataSourceProperties.isLogSlowSql());
                    filter.setMergeSql(druidDataSourceProperties.isMergeSql());
                    filter.setSlowSqlMillis(druidDataSourceProperties.getSlowSqlMillis());
                    List list = new ArrayList<>();
                    list.add(filter);
                    result.setProxyFilters(list);
                }
     
            } catch (Exception e) {
     
                logger.error("数据源加载失败:", e);
     
            } finally {
                result.close();
            }
     
     
            return result;
        }
    }

    注意主从数据库的bean name

    配置DynamicDataSource 

    • targetDataSources 存放数据源的k-v对

    • defaultTargetDataSource 存放默认数据源

    配置事务管理器和SqlSessionFactoryBean

    @Configuration
    public class DynamicDataSourceConfig {
        private static final String MAPPER_LOCATION = "classpath*:sqlmap/dao/*Mapper.xml";
     
        @Bean(name = "dynamicDataSource")
        public DynamicDataSource dynamicDataSource(@Qualifier("masterDataSource") DruidDataSource masterDataSource,
                                                   @Qualifier("slaveDataSource") DruidDataSource slaveDataSource) {
            Map targetDataSource = new HashMap<>();
            DynamicDataSourceContextHolder.dataSourceIds.add("masterDataSource");
            targetDataSource.put("masterDataSource", masterDataSource);
            DynamicDataSourceContextHolder.dataSourceIds.add("slaveDataSource");
            targetDataSource.put("slaveDataSource", slaveDataSource);
            DynamicDataSource dataSource = new DynamicDataSource();
            dataSource.setTargetDataSources(targetDataSource);
            dataSource.setDefaultTargetDataSource(masterDataSource);
            return dataSource;
        }
     
        @Primary
        @Bean(name = "javaTransactionManager")
        @ConditionalOnMissingBean(name = "javaTransactionManager")
        public DataSourceTransactionManager transactionManager(@Qualifier("dynamicDataSource") DynamicDataSource druidDataSource) {
            return new DataSourceTransactionManager(druidDataSource);
        }
     
        @Bean(name = "sqlSessionFactoryBean")
        public SqlSessionFactoryBean myGetSqlSessionFactory(@Qualifier("dynamicDataSource") DynamicDataSource  dataSource) {
            SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
            ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
            try {
                sqlSessionFactoryBean.setMapperLocations(resolver.getResources(MAPPER_LOCATION));
            } catch (IOException e) {
                e.printStackTrace();
            }
            sqlSessionFactoryBean.setDataSource(dataSource);
            return sqlSessionFactoryBean;
        }
    }

    定义一个注解用于指定数据源

    @Target({ ElementType.METHOD, ElementType.TYPE })
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    public @interface TargetDataSource {
        String value();
    }

    切面的业务逻辑。注意指定order,以确保在开启事务之前执行 。

    @Aspect
    @Slf4j
    @Order(-1)
    @Component
    public class DataSourceAop {
     
        @Before("@annotation(targetDataSource)")
        public void changeDataSource(JoinPoint point, TargetDataSource targetDataSource) {
            String dsId = targetDataSource.value();
            if (!DynamicDataSourceContextHolder.containsDataSource(dsId)) {
                log.error("数据源[{}]不存在,使用默认数据源 > {}" + targetDataSource.value() + point.getSignature());
            } else {
                log.info("UseDataSource : {} > {}" + targetDataSource.value() + point.getSignature());
                DynamicDataSourceContextHolder.setDataSourceType(targetDataSource.value());
     
            }
        }
     
        @After("@annotation(targetDataSource)")
        public void restoreDataSource(JoinPoint point, TargetDataSource targetDataSource) {
            log.info("RevertDataSource : {} > {}"+targetDataSource.value()+point.getSignature());
            DynamicDataSourceContextHolder.clearDataSourceType();
        }
    }

    以上略去了pom.xml和application.yml

    使用示例

        @Resource
        private ShopBillDOMapper shopBillDOMapper;
     
    //使用默认数据源
        public ShopBillBO queryTestData(Integer id){
     
            return shopBillDOMapper.getByShopBillId(id);
        }
     
    //切换到指定的数据源
        @TargetDataSource("slaveDataSource")
        public ShopBill queryTestData2(Integer id){
            return shopBillDOMapper.getByShopBillId(id);
        }

    如果返回不同的结果就成功了!

    本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系bd@zhengruan.com
    作者最新文章
    编程开发
    相关文章 更多
    精品专题 更多
    装机必备

    正软商城装机必备专区,精选办公、浏览器、安全防护、影音播放、压缩解压、设计创作和系统工具等电脑常用正版软件,帮助用户快速完成新电脑软件配置。

    Windows

    正软商城Windows软件专区,汇集适用于Windows电脑的办公、设计、安全防护、影音播放、开发工具和系统优化软件,提供软件介绍、系统要求、正版授权及购买下载服务。

    PDF教程

    正软商城PDF教程频道提供PDF编辑、转换、合并、拆分、压缩及格式处理方法,同时介绍常用PDF软件和工具的使用技巧。

    macOS软件

    正软商城macOS软件专区,精选适用于Mac电脑的办公、设计、影音、效率、开发和系统工具,提供软件功能介绍、macOS兼容版本、正版授权及购买下载服务。

    IOS软件

    正软商城iOS软件专区,精选适用于iPhone和iPad的办公、学习、影音、设计、效率及AI应用,提供功能介绍、适用设备、系统要求和正版获取方式等信息。

    AI

    正软商城AI软件专区,汇集AI写作、AI绘画、AI视频、AI办公、AI编程、AI翻译、智能客服和数据分析等人工智能工具,提供功能介绍、适用平台、收费方式及正版购买信息。

    Mac软件 更多
    Aperty macOS版
    Aperty macOS版

    Aperty 是 Skylum 推出的 AI 人像修图软件,支持自然肤质修饰、瑕疵处理、面部与身体调整、预设及批量同步。

    火山引擎 网页版
    火山引擎 网页版

    火山引擎是字节跳动旗下企业级云与AI服务平台。聚焦大模型核心能力,依托字节自研豆包多模态大模型,凭借火山方舟一站式平台,提供模型精调、推理部署、智能应用搭建等全链路服务,结合高性能AI算力,助力各行业快速落地大模型数字化与智能化应用。

    立刻MV 网页版
    立刻MV 网页版

    立刻MV 面向音乐人、内容创作者和品牌团队,帮助用户低成本完成歌曲 MV、歌词视频、AI 分镜、图生视频与最终合成。

    蛙蛙写作 网页版
    蛙蛙写作 网页版

    蛙蛙写作 AI 创作工具,覆盖小说、剧本、文案,一键生成文稿,打通文字转视频全流程,高效解决创作难题。

    讯飞智作 网页版
    讯飞智作 网页版

    讯飞智作是一款基于语音合成技术、虚拟人驱动技术与数字人形象声音构建能力的 AI 数字人音视频创作平台。

    超级简历WonderCV 网页版
    超级简历WonderCV 网页版

    超级简历WonderCV是面向应届生和AI小白的智能求职平台,覆盖简历、面试与职业规划。

    音述AI 网页版
    音述AI 网页版

    音述AI,是一个以“用声音述说故事”为核心的 AI 音乐创作与声音分享社区。

    AionClaw macOS版
    AionClaw macOS版

    AionClaw 是可在桌面端运行的任务型 AI 助手,通过数字专家与技能市场组合办公、创作、数据和开发能力。

    Loomy macOS版
    Loomy macOS版

    Loomy 是科大讯飞推出的桌面 AI 助手,可通过对话、任务与工作目录协助处理办公、内容创作和资料整理。

    AirBuddy 3 macOS版
    AirBuddy 3 macOS版

    AirBuddy 3 是面向 macOS 的蓝牙外设增强工具,可集中查看 AirPods、Beats 与苹果设备电量,提供快速连接、播放控制、电量提醒、桌面小组件和多台 Mac 外设接力等功能。

    AirServer macOS版
    AirServer macOS版

    AirServer macOS版可把 Mac 转换为无线投屏接收端,通过 AirPlay 或 Google Cast 接收手机、平板和电脑画面,并支持多设备同时连接、高清镜像及会话录制,适合家庭娱乐、课堂教学、会议演示和应用展示。

    AnyDesk macOS版
    AnyDesk macOS版

    AnyDesk macOS版是一款适用于远程办公、设备维护和客户支持的远程桌面工具,可连接并操作异地计算机,支持文件传输、无人值守访问、会话权限控制及跨平台协作。

    WINDOWS 更多
    讯飞绘文 网页版
    讯飞绘文 网页版

    讯飞绘文网页版是科大讯飞推出的AI图文创作与内容运营工具,覆盖热点选题、文章生成、稿件校对、智能配图、排版发布和数据复盘等环节,适合自媒体创作者及内容团队在线使用。

    Maya(Autodesk Maya) Windows版
    Maya(Autodesk Maya) Windows版

    Autodesk Maya 是面向影视、电视、动画和游戏行业的专业三维制作软件,集多边形与 NURBS 建模、角色绑定、关键帧和动作捕捉动画、Bifrost 特效模拟、材质开发及 Arnold 渲染于一体,

    Aperty Windows版
    Aperty Windows版

    Aperty 是 Skylum 推出的 AI 人像修图软件,支持自然肤质修饰、瑕疵处理、面部与身体调整、预设及批量同步。

    火山引擎 网页版
    火山引擎 网页版

    火山引擎是字节跳动旗下企业级云与AI服务平台。聚焦大模型核心能力,依托字节自研豆包多模态大模型,凭借火山方舟一站式平台,提供模型精调、推理部署、智能应用搭建等全链路服务,结合高性能AI算力,助力各行业快速落地大模型数字化与智能化应用。

    立刻MV 网页版
    立刻MV 网页版

    立刻MV 面向音乐人、内容创作者和品牌团队,帮助用户低成本完成歌曲 MV、歌词视频、AI 分镜、图生视频与最终合成。

    蛙蛙写作 网页版
    蛙蛙写作 网页版

    蛙蛙写作 AI 创作工具,覆盖小说、剧本、文案,一键生成文稿,打通文字转视频全流程,高效解决创作难题。

    讯飞智作 网页版
    讯飞智作 网页版

    讯飞智作是一款基于语音合成技术、虚拟人驱动技术与数字人形象声音构建能力的 AI 数字人音视频创作平台。

    超级简历WonderCV 网页版
    超级简历WonderCV 网页版

    超级简历WonderCV是面向应届生和AI小白的智能求职平台,覆盖简历、面试与职业规划。

    音述AI 网页版
    音述AI 网页版

    音述AI,是一个以“用声音述说故事”为核心的 AI 音乐创作与声音分享社区。

    AionClaw Windows版
    AionClaw Windows版

    AionClaw 是可在桌面端运行的任务型 AI 助手,通过数字专家与技能市场组合办公、创作、数据和开发能力。

    Loomy Windows版
    Loomy Windows版

    Loomy 是科大讯飞推出的桌面 AI 助手,可通过对话、任务与工作目录协助处理办公、内容创作和资料整理。

    AirServer Windows版
    AirServer Windows版

    AirServer Windows版可把电脑变成AirPlay、Google Cast和Miracast无线投屏接收端,适合会议演示、课堂教学及家庭大屏分享。发送设备通常无需另装客户端,并可同时接收和智能排列多个镜像会话。