springboot多数据源根据开关控制方法访问的数据源

有个需求需要通过开关控制需要访问的数据源,此处参考DS多数据源,采用注解加aop切面实现此功能。

配置文件开关:

XML 复制代码
slave-config:
  mainSlaveSwitch: true

配置开关类:

java 复制代码
@Component
@RefreshScope
@Data
@ConfigurationProperties("slave-config")
public class SlaveConfig {
    private boolean mainSlaveSwitch=false;
}

多数据源配置:

XML 复制代码
  datasource:
    dynamic:
      primary: master
      datasource:
        master:
          url: jdbc:mysql://xxxx:3306/order?useUnicode=true&characterEncoding=utf-8&useSSL=false
          username: gac_travel_dev
          password: gac@6666
          driverClassName: com.mysql.jdbc.Driver
          type: com.alibaba.druid.pool.DruidDataSource
          druid:
            initialSize: 10
            maxActive: 20
            minIdle: 5
            maxWait: 1000
            minEvictableIdleTimeMillis: 300000
            useGlobalDataSourceStat: true
            timeBetweenEvictionRunsMillis: 60000
            validationQuery: select 'x'
            testOnBorrow: true
            testOnReturn: true
            testWhileIdle: true
        slave:
          url: jdbc:mysql://xxxx:3306/order/gac_order?useUnicode=true&characterEncoding=utf-8&useSSL=false
          username: gac_dev_read
          password: gac@6666
          type: com.alibaba.druid.pool.DruidDataSource
          druid:
            initialSize: 10
            maxActive: 20
            minIdle: 5
            maxWait: 1000
            minEvictableIdleTimeMillis: 300000
            useGlobalDataSourceStat: true
            timeBetweenEvictionRunsMillis: 60000
            validationQuery: select 'x'
            testOnBorrow: true
            testOnReturn: true
            testWhileIdle: true
        mainslave:
          url: jdbc:mysql://xxxx:3306/order/gac_order?useUnicode=true&characterEncoding=utf-8&useSSL=false
          username: gac_travel_test
          password: gac@6666
          type: com.alibaba.druid.pool.DruidDataSource
          druid:
            initialSize: 10
            maxActive: 20
            minIdle: 5
            maxWait: 1000
            minEvictableIdleTimeMillis: 300000
            useGlobalDataSourceStat: true
            timeBetweenEvictionRunsMillis: 60000
            validationQuery: select 'x'
            testOnBorrow: true
            testOnReturn: true
            testWhileIdle: true

多数据源静态类(不是必须的):

XML 复制代码
public interface DBTypeConst {

    /**
     * 主库
     */
    String MASTER = "master";
    /**
     * 主库的从库
     */
    String MAIN_SLAVE = "mainslave";
    /**
     * 从库
     */
    String SLAVE = "slave";
    

}

多数据源注解:

java 复制代码
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface DynamicDataSource {
}

AOP切面:

java 复制代码
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;

@Aspect
@Component
@Slf4j
public class DynamicDataSourceAspect {
    @Autowired
    SlaveConfig slaveConfig;
    @Around("@annotation(dynamicDataSource)")
    public Object switchDataSource(ProceedingJoinPoint joinPoint, DynamicDataSource dynamicDataSource) throws Throwable {
        if(slaveConfig.isMainSlaveSwitch()){
            log.info("DynamicDataSourceAspect:{}",DBTypeConst.MAIN_SLAVE);
            DynamicDataSourceContextHolder.push(DBTypeConst.MAIN_SLAVE);
        }else{
            log.info("DynamicDataSourceAspect:{}",DBTypeConst.SLAVE);
            DynamicDataSourceContextHolder.push(DBTypeConst.SLAVE);
        }
        try {
            return joinPoint.proceed();
        } finally {
            DynamicDataSourceContextHolder.clear();
        }
    }
}

此处使用时要多测试防止异常

相关推荐
_星辰大海乀几秒前
表的设计、聚合函数
java·数据结构·数据库·sql·mysql·数据库开发
IT成长史9 分钟前
deepseek梳理java高级开发工程师微服务面试题-进阶版
java·spring cloud·微服务
zkmall19 分钟前
Java + 鸿蒙双引擎:ZKmall开源商城如何定义下一代B2C商城技术标准?
java·开源·harmonyos
陌路物是人非20 分钟前
uniapp取消浏览自动填充
java·服务器·uni-app
獨枭22 分钟前
使用 163 邮箱实现 Spring Boot 邮箱验证码登录
java·spring boot·后端
伍六星22 分钟前
maven和npm区别是什么
java·npm·maven
才知山高路远26 分钟前
Java - Junit框架
java·junit·log4j
维基框架27 分钟前
Spring Boot 封装 MinIO 工具
java·spring boot·后端
秋野酱27 分钟前
基于javaweb的SpringBoot酒店管理系统设计与实现(源码+文档+部署讲解)
java·spring boot·后端
关于不上作者榜就原神启动那件事28 分钟前
Java基础学习
java·开发语言·学习