当前位置: 代码网 > it编程>编程语言>Java > SpringBoot实现动态切换数据源的示例代码

SpringBoot实现动态切换数据源的示例代码

2025年08月17日 Java 我要评论
最近在做业务需求时,需要从不同的数据库中获取数据然后写入到当前数据库中,因此涉及到切换数据源问题。本来想着使用mybatis-plus中提供的动态数据源springboot的starter:dynam

最近在做业务需求时,需要从不同的数据库中获取数据然后写入到当前数据库中,因此涉及到切换数据源问题。本来想着使用mybatis-plus中提供的动态数据源springboot的starter:dynamic-datasource-spring-boot-starter来实现。

结果引入后发现由于之前项目环境问题导致无法使用。然后研究了下数据源切换代码,决定自己采用threadlocal+abstractroutingdatasource来模拟实现dynamic-datasource-spring-boot-starter中线程数据源切换。

1 简介

上述提到了threadlocal和abstractroutingdatasource,我们来对其进行简单介绍下。

threadlocal:想必大家必不会陌生,全称:thread local variable。主要是为解决多线程时由于并发而产生数据不一致问题。threadlocal为每个线程提供变量副本,确保每个线程在某一时间访问到的不是同一个对象,这样做到了隔离性,增加了内存,但大大减少了线程同步时的性能消耗,减少了线程并发控制的复杂程度。

  • threadlocal作用:在一个线程中共享,不同线程间隔离
  • threadlocal原理:threadlocal存入值时,会获取当前线程实例作为key,存入当前线程对象中的map中。

abstractroutingdatasource:根据用户定义的规则选择当前的数据源,

作用:在执行查询之前,设置使用的数据源,实现动态路由的数据源,在每次数据库查询操作前执行它的抽象方法determinecurrentlookupkey(),决定使用哪个数据源。

2 代码实现

程序环境:

  • springboot2.4.8
  • mybatis-plus3.2.0
  • druid1.2.6
  • lombok1.18.20
  • commons-lang3 3.10

2.1 实现threadlocal

创建一个类用于实现threadlocal,主要是通过get,set,remove方法来获取、设置、删除当前线程对应的数据源。

/**
 * @author: jiangjs
 * @description:
 * @date: 2023/7/27 11:21
 **/
public class datasourcecontextholder {
    //此类提供线程局部变量。这些变量不同于它们的正常对应关系是每个线程访问一个线程(通过get、set方法),有自己的独立初始化变量的副本。
    private static final threadlocal<string> datasource_holder = new threadlocal<>();

    /**
     * 设置数据源
     * @param datasourcename 数据源名称
     */
    public static void setdatasource(string datasourcename){
        datasource_holder.set(datasourcename);
    }

    /**
     * 获取当前线程的数据源
     * @return 数据源名称
     */
    public static string getdatasource(){
        return datasource_holder.get();
    }

    /**
     * 删除当前数据源
     */
    public static void removedatasource(){
        datasource_holder.remove();
    }

}

2.2 实现abstractroutingdatasource

定义一个动态数据源类实现abstractroutingdatasource,通过determinecurrentlookupkey方法与上述实现的threadlocal类中的get方法进行关联,实现动态切换数据源。

/**
 * @author: jiangjs
 * @description: 实现动态数据源,根据abstractroutingdatasource路由到不同数据源中
 * @date: 2023/7/27 11:18
 **/
public class dynamicdatasource extends abstractroutingdatasource {

    public dynamicdatasource(datasource defaultdatasource,map<object, object> targetdatasources){
        super.setdefaulttargetdatasource(defaultdatasource);
        super.settargetdatasources(targetdatasources);
    }

    @override
    protected object determinecurrentlookupkey() {
        return datasourcecontextholder.getdatasource();
    }
}

上述代码中,还实现了一个动态数据源类的构造方法,主要是为了设置默认数据源,以及以map保存的各种目标数据源。其中map的key是设置的数据源名称,value则是对应的数据源(datasource)。

2.3 配置数据库

application.yml中配置数据库信息:

#设置数据源
spring:
  datasource:
    type: com.alibaba.druid.pool.druiddatasource
    druid:
      master:
        url: jdbc:mysql://xxxxxx:3306/test1?characterencoding=utf-8&allowmultiqueries=true&zerodatetimebehavior=converttonull&usessl=false
        username: root
        password: 123456
        driver-class-name: com.mysql.cj.jdbc.driver
      slave:
        url: jdbc:mysql://xxxxx:3306/test2?characterencoding=utf-8&allowmultiqueries=true&zerodatetimebehavior=converttonull&usessl=false
        username: root
        password: 123456
        driver-class-name: com.mysql.cj.jdbc.driver
      initial-size: 15
      min-idle: 15
      max-active: 200
      max-wait: 60000
      time-between-eviction-runs-millis: 60000
      min-evictable-idle-time-millis: 300000
      validation-query: ""
      test-while-idle: true
      test-on-borrow: false
      test-on-return: false
      pool-prepared-statements: false
      connection-properties: false
/**
 * @author: jiangjs
 * @description: 设置数据源
 * @date: 2023/7/27 11:34
 **/
@configuration
public class datesourceconfig {

    @bean
    @configurationproperties("spring.datasource.druid.master")
    public datasource masterdatasource(){
        return druiddatasourcebuilder.create().build();
    }

    @bean
    @configurationproperties("spring.datasource.druid.slave")
    public datasource slavedatasource(){
        return druiddatasourcebuilder.create().build();
    }

    @bean(name = "dynamicdatasource")
    @primary
    public dynamicdatasource createdynamicdatasource(){
        map<object,object> datasourcemap = new hashmap<>();
        datasource defaultdatasource = masterdatasource();
        datasourcemap.put("master",defaultdatasource);
        datasourcemap.put("slave",slavedatasource());
        return new dynamicdatasource(defaultdatasource,datasourcemap);
    }

}

通过配置类,将配置文件中的配置的数据库信息转换成datasource,并添加到dynamicdatasource中,同时通过@bean将dynamicdatasource注入spring中进行管理,后期在进行动态数据源添加时,会用到。

2.4 测试

在主从两个测试库中,分别添加一张表test_user,里面只有一个字段user_name

create table test_user(
  user_name varchar(255) not null comment '用户名'
)

在主库添加信息:

insert into test_user (user_name) value ('master');

从库中添加信息:

insert into test_user (user_name) value ('slave');

我们创建一个getdata的方法,参数就是需要查询数据的数据源名称。

@getmapping("/getdata.do/{datasourcename}")
public string getmasterdata(@pathvariable("datasourcename") string datasourcename){
    datasourcecontextholder.setdatasource(datasourcename);
    testuser testuser = testusermapper.selectone(null);
    datasourcecontextholder.removedatasource();
    return testuser.getusername();
}

其他的mapper和实体类大家自行实现。

执行结果:

1、传递master时:

2、传递slave时:

通过执行结果,我们看到传递不同的数据源名称,查询对应的数据库是不一样的,返回结果也不一样。

在上述代码中,我们看到datasourcecontextholder.setdatasource(datasourcename); 来设置了当前线程需要查询的数据库,通过datasourcecontextholder.removedatasource(); 来移除当前线程已设置的数据源。使用过mybatis-plus动态数据源的小伙伴,应该还记得我们在使用切换数据源时会使用到dynamicdatasourcecontextholder.push(string ds);dynamicdatasourcecontextholder.poll(); 这两个方法,翻看源码我们会发现其实就是在使用threadlocal时使用了栈,这样的好处就是能使用多数据源嵌套,这里就不带大家实现了,有兴趣的小伙伴可以看看mybatis-plus中动态数据源的源码。

注:启动程序时,小伙伴不要忘记将springboot自动添加数据源进行排除哦,否则会报循环依赖问题。

@springbootapplication(exclude = datasourceautoconfiguration.class)

2.5 优化调整

2.5.1 注解切换数据源

在上述中,虽然已经实现了动态切换数据源,但是我们会发现如果涉及到多个业务进行切换数据源的话,我们就需要在每一个实现类中添加这一段代码。

说到这有小伙伴应该就会想到使用注解来进行优化,接下来我们来实现一下。

2.5.1.1 定义注解

我们就用mybatis动态数据源切换的注解:ds,代码如下:

/**
 * @author: jiangjs
 * @description:
 * @date: 2023/7/27 14:39
 **/
@target({elementtype.method,elementtype.type})
@retention(retentionpolicy.runtime)
@documented
@inherited
public @interface ds {
    string value() default "master";
}

2.5.1.2 实现aop

@aspect
@component
@slf4j
public class dsaspect {

    @pointcut("@annotation(com.jiashn.dynamic_datasource.dynamic.aop.ds)")
    public void dynamicdatasource(){}

    @around("dynamicdatasource()")
    public object datasourcearound(proceedingjoinpoint point) throws throwable {
        methodsignature signature = (methodsignature)point.getsignature();
        method method = signature.getmethod();
        ds ds = method.getannotation(ds.class);
        if (objects.nonnull(ds)){
            datasourcecontextholder.setdatasource(ds.value());
        }
        try {
            return point.proceed();
        } finally {
            datasourcecontextholder.removedatasource();
        }
    }
}

代码使用了@around,通过proceedingjoinpoint获取注解信息,拿到注解传递值,然后设置当前线程的数据源。对aop不了解的小伙伴可以自行google或百度。

2.5.1.3 测试

添加两个测试方法:

@getmapping("/getmasterdata.do")
public string getmasterdata(){
    testuser testuser = testusermapper.selectone(null);
    return testuser.getusername();
}

@getmapping("/getslavedata.do")
@ds("slave")
public string getslavedata(){
    testuser testuser = testusermapper.selectone(null);
    return testuser.getusername();
}

由于@ds中设置的默认值是:master,因此在调用主数据源时,可以不用进行添加。

执行结果:

1、调用getmasterdata.do方法:

2、调用getslavedata.do方法:

通过执行结果,我们通过@ds也进行了数据源的切换,实现了mybatis-plus动态切换数据源中的通过注解切换数据源的方式。

2.5.2 动态添加数据源

业务场景 :有时候我们的业务会要求我们从保存有其他数据源的数据库表中添加这些数据源,然后再根据不同的情况切换这些数据源。

因此我们需要改造下dynamicdatasource来实现动态加载数据源。

2.5.2.1 数据源实体

/**
 * @author: jiangjs
 * @description: 数据源实体
 * @date: 2023/7/27 15:55
 **/
@data
@accessors(chain = true)
public class datasourceentity {

    /**
     * 数据库地址
     */
    private string url;
    /**
     * 数据库用户名
     */
    private string username;
    /**
     * 密码
     */
    private string password;
    /**
     * 数据库驱动
     */
    private string driverclassname;
    /**
     * 数据库key,即保存map中的key
     */
    private string key;
}

实体中定义数据源的一般信息,同时定义一个key用于作为dynamicdatasource中map中的key。

2.5.2.2 修改dynamicdatasource

/**
 * @author: jiangjs
 * @description: 实现动态数据源,根据abstractroutingdatasource路由到不同数据源中
 * @date: 2023/7/27 11:18
 **/
@slf4j
public class dynamicdatasource extends abstractroutingdatasource {

    private final map<object,object> targetdatasourcemap;

    public dynamicdatasource(datasource defaultdatasource,map<object, object> targetdatasources){
        super.setdefaulttargetdatasource(defaultdatasource);
        super.settargetdatasources(targetdatasources);
        this.targetdatasourcemap = targetdatasources;
    }

    @override
    protected object determinecurrentlookupkey() {
        return datasourcecontextholder.getdatasource();
    }

    /**
     * 添加数据源信息
     * @param datasources 数据源实体集合
     * @return 返回添加结果
     */
    public void createdatasource(list<datasourceentity> datasources){
        try {
            if (collectionutils.isnotempty(datasources)){
                for (datasourceentity ds : datasources) {
                    //校验数据库是否可以连接
                    class.forname(ds.getdriverclassname());
                    drivermanager.getconnection(ds.geturl(),ds.getusername(),ds.getpassword());
                    //定义数据源
                    druiddatasource datasource = new druiddatasource();
                    beanutils.copyproperties(ds,datasource);
                    //申请连接时执行validationquery检测连接是否有效,这里建议配置为true,防止取到的连接不可用
                    datasource.settestonborrow(true);
                    //建议配置为true,不影响性能,并且保证安全性。
                    //申请连接的时候检测,如果空闲时间大于timebetweenevictionrunsmillis,执行validationquery检测连接是否有效。
                    datasource.settestwhileidle(true);
                    //用来检测连接是否有效的sql,要求是一个查询语句。
                    datasource.setvalidationquery("select 1 ");
                    datasource.init();
                    this.targetdatasourcemap.put(ds.getkey(),datasource);
                }
                super.settargetdatasources(this.targetdatasourcemap);
                // 将targetdatasources中的连接信息放入resolveddatasources管理
                super.afterpropertiesset();
                return boolean.true;
            }
        }catch (classnotfoundexception | sqlexception e) {
            log.error("---程序报错---:{}", e.getmessage());
        }
        return boolean.false;
    }

    /**
     * 校验数据源是否存在
     * @param key 数据源保存的key
     * @return 返回结果,true:存在,false:不存在
     */
    public boolean existsdatasource(string key){
        return objects.nonnull(this.targetdatasourcemap.get(key));
    }
}

在改造后的dynamicdatasource中,我们添加可以一个 private final map<object,object> targetdatasourcemap,这个map会在添加数据源的配置文件时将创建的map数据源信息通过dynamicdatasource构造方法进行初始赋值,即:datesourceconfig类中的createdynamicdatasource()方法中。

同时我们在该类中添加了一个createdatasource方法,进行数据源的创建,并添加到map中,再通过super.settargetdatasources(this.targetdatasourcemap) ;进行目标数据源的重新赋值。

2.5.2.3 动态添加数据源

上述代码已经实现了添加数据源的方法,那么我们来模拟通过从数据库表中添加数据源,然后我们通过调用加载数据源的方法将数据源添加进数据源map中。

在主数据库中定义一个数据库表,用于保存数据库信息。

为了方便,我们将之前的从库录入到数据库中,修改数据库名称。

insert into test_db_info(url, username, password,driver_class_name, name)
value ('jdbc:mysql://xxxxx:3306/test2?characterencoding=utf-8&allowmultiqueries=true&zerodatetimebehavior=converttonull&usessl=false',
       'root','123456','com.mysql.cj.jdbc.driver','add_slave')

数据库表对应的实体、mapper,小伙伴们自行添加。

启动springboot时添加数据源:

/**
 * @author: jiangjs
 * @description:
 * @date: 2023/7/27 16:56
 **/
@component
public class loaddatasourcerunner implements commandlinerunner {
    @resource
    private dynamicdatasource dynamicdatasource;
    @resource
    private testdbinfomapper testdbinfomapper;
    @override
    public void run(string... args) throws exception {
        list<testdbinfo> testdbinfos = testdbinfomapper.selectlist(null);
        if (collectionutils.isnotempty(testdbinfos)) {
            list<datasourceentity> ds = new arraylist<>();
            for (testdbinfo testdbinfo : testdbinfos) {
                datasourceentity sourceentity = new datasourceentity();
                beanutils.copyproperties(testdbinfo,sourceentity);
                sourceentity.setkey(testdbinfo.getname());
                ds.add(sourceentity);
            }
            dynamicdatasource.createdatasource(ds);
        }
    }
}

经过上述springboot启动后,已经将数据库表中的数据添加到动态数据源中,我们调用之前的测试方法,将数据源名称作为参数传入看看执行结果。

2.5.2.4 测试

通过测试我们发现数据库表中的数据库被动态加入了数据源中,小伙伴可以愉快地随意添加数据源了。

到此这篇关于springboot实现动态切换数据源的示例代码的文章就介绍到这了,更多相关springboot动态切换数据源内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com