125 如何运行时实时切换数据库(实时切换影子库)

前言

最近有 流量回放 的使用需求

然后 看了一下 影子库 的相关知识

然后 在考虑 怎么运行时 直接通过 配置项的更新 来切换 业务项目的数据库路由是走 生产库, 还是影子库

搜索了一下 大多数的使用貌似 都不怎么 符合这个灵活的需求, 因此 组合根据这里的需要 造个轮子

复制代码
jerry.shadow.db.feature.enabled 作为一个 影子库切换 feature 的一个总开关, 关闭的话 则使用默认的 DataSource, SqlSessionFactory 不会有任何额外的业务影响, 主要是用于 假设这个 feature 出现什么问题, 可以及时的无副作用的关掉 
复制代码
jerry.shadow.db.use-shadow-db 配置为 true 表示使用影子库, 其他情况表示使用默认库 

JerryShadowDBConfig

这里是直接创建的 SimpleDataSource, 实际业务中一般是 使用的 Druid 之类的数据源

拷贝一下 其对应的 DruidDataSourceProperties, 以及 DruidDataSourceWrapper 然后 更新一下 prefix, 然后 构造一下对应的 bean 即可

这里主要的目的是构造 JerryShadowDBSqlSessionFactory 来作为项目的 SqlSessionFactory, 其中会根据配置进行路由是 业务数据库 还是 影子数据库

复制代码
package com.hx.boot.config;

/**
 * MyBatisConfig
 *
 * @author Jerry.X.He <970655147@qq.com>
 * @version 1.0
 * @date 2025-09-04 10:55
 */
@Configuration
@ConditionalOnProperty(name = "jerry.shadow.db.feature.enabled", havingValue = "true")
public class JerryShadowDBConfig {

    @Resource
    private ApplicationContext applicationContext;

    @Bean
    public DataSource defaultDataSource() {
        SimpleDriverDataSource dataSource = new SimpleDriverDataSource();
        dataSource.setDriverClass(Driver.class);
        dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8&relaxAutoCommit=true&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true");
        dataSource.setUsername("root");
        dataSource.setPassword("postgres");
        return dataSource;
    }

    @Bean
    public SqlSessionFactory defaultSqlSessionFactory(@Qualifier("defaultDataSource") DataSource dataSource) throws Exception {
        MybatisSqlSessionFactoryBean factory = new MybatisSqlSessionFactoryBean();
        factory.setDataSource(dataSource);
        return factory.getObject();
    }

    @Bean
    public DataSource shadowDataSource() {
        SimpleDriverDataSource dataSource = new SimpleDriverDataSource();
        dataSource.setDriverClass(Driver.class);
        dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/shadow_db?useUnicode=true&characterEncoding=utf-8&relaxAutoCommit=true&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true");
        dataSource.setUsername("root");
        dataSource.setPassword("postgres");
        return dataSource;
    }

    @Bean
    public SqlSessionFactory shadowSqlSessionFactory(@Qualifier("shadowDataSource") DataSource dataSource) throws Exception {
        MybatisSqlSessionFactoryBean factory = new MybatisSqlSessionFactoryBean();
        factory.setDataSource(dataSource);
        return factory.getObject();
    }

    @Bean
    @Primary
    public SqlSessionFactory jerryShadowDBSqlSessionFactory(@Qualifier("defaultSqlSessionFactory") SqlSessionFactory defaultSqlSessionFactory,
                                                            @Qualifier("shadowSqlSessionFactory") SqlSessionFactory shadowSqlSessionFactory) throws Exception {
        return new JerryShadowDBSqlSessionFactory(defaultSqlSessionFactory, shadowSqlSessionFactory, applicationContext.getEnvironment());
    }


}

JerryShadowDBSqlSessionFactory

组合业务数据库 和 影子数据库

实时 根据上下文的配置进行路由

复制代码
package com.hx.boot.config;

/**
 * JerryShadowDBSqlSessionFactory
 *
 * @author Jerry.X.He <970655147@qq.com>
 * @version 1.0
 * @date 2025-09-04 10:55
 */
public class JerryShadowDBSqlSessionFactory implements SqlSessionFactory {

    private SqlSessionFactory defaultSqlSessionFactory;

    private SqlSessionFactory shadowSqlSessionFactory;

    private Environment env;

    public JerryShadowDBSqlSessionFactory(SqlSessionFactory defaultSqlSessionFactory, SqlSessionFactory shadowSqlSessionFactory, Environment env) {
        this.defaultSqlSessionFactory = defaultSqlSessionFactory;
        this.shadowSqlSessionFactory = shadowSqlSessionFactory;
        this.env = env;
    }

    @Override
    public SqlSession openSession() {
        return chooseSqlSessionFactory().openSession();
    }

    @Override
    public SqlSession openSession(boolean autoCommit) {
        return chooseSqlSessionFactory().openSession(autoCommit);
    }

    @Override
    public SqlSession openSession(Connection connection) {
        return chooseSqlSessionFactory().openSession(connection);
    }

    @Override
    public SqlSession openSession(TransactionIsolationLevel level) {
        return chooseSqlSessionFactory().openSession(level);
    }

    @Override
    public SqlSession openSession(ExecutorType execType) {
        return chooseSqlSessionFactory().openSession(execType);
    }

    @Override
    public SqlSession openSession(ExecutorType execType, boolean autoCommit) {
        return chooseSqlSessionFactory().openSession(execType, autoCommit);
    }

    @Override
    public SqlSession openSession(ExecutorType execType, TransactionIsolationLevel level) {
        return chooseSqlSessionFactory().openSession(execType, level);
    }

    @Override
    public SqlSession openSession(ExecutorType execType, Connection connection) {
        return chooseSqlSessionFactory().openSession(execType, connection);
    }

    @Override
    public Configuration getConfiguration() {
        return chooseSqlSessionFactory().getConfiguration();
    }


    private SqlSessionFactory chooseSqlSessionFactory() {
        String useShadowDb = env.getProperty("jerry.shadow.db.use-shadow-db");
        if("true".equalsIgnoreCase(useShadowDb)) {
            return shadowSqlSessionFactory;
        }
        return defaultSqlSessionFactory;
    }


}

效果测试

测试的 api 如下, 很简单 就是 mybatis 的 Mapper 进行 查询

test/shadow_db 中数据库分别如下

复制代码
jerry.shadow.db.feature.enabled 作为一个 影子库切换 feature 的一个总开关, 关闭的话 则使用默认的 DataSource, SqlSessionFactory 不会有任何额外的业务影响, 主要是用于 假设这个 feature 出现什么问题, 可以及时的无副作用的关掉 
复制代码
jerry.shadow.db.use-shadow-db 配置为 false/true 的结果分别如下 

可以看到 实现了 数据库的切换

相关推荐
大阿明7 小时前
Spring Boot(快速上手)
java·spring boot·后端
bearpping8 小时前
Java进阶,时间与日期,包装类,正则表达式
java
邵奈一8 小时前
清明纪念·时光信笺——项目运行指南
java·实战·项目
sunwenjian8868 小时前
Java进阶——IO 流
java·开发语言·python
sinat_255487818 小时前
读者、作家 Java集合学习笔记
java·笔记·学习
皮皮林5518 小时前
如何画出一张优秀的架构图?(老鸟必备)
java
百锦再8 小时前
Java 并发编程进阶,从线程池、锁、AQS 到并发容器与性能调优全解析
java·开发语言·jvm·spring·kafka·tomcat·maven
森林猿9 小时前
java-modbus-读取-modbus4j
java·网络·python
tobias.b9 小时前
计算机基础知识-数据结构
java·数据结构·考研
reembarkation9 小时前
光标在a-select,鼠标已经移出,下拉框跟随页面滚动
java·数据库·sql