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();
        }
    }
}

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

相关推荐
weixin_446122469 分钟前
浏览器播放监控画面
java·spring boot
lpfasd12313 分钟前
模板方法模式(Template Method Pattern)
java·开发语言·设计模式·模板方法模式
hn小菜鸡41 分钟前
LeetCode 2529.正整数和负整数的最大计数
java·算法·leetcode
zh_199951 小时前
Spark面试精讲(上)
java·大数据·数据仓库·python·spark·数据库开发·数据库架构
小猫咪怎么会有坏心思呢1 小时前
华为OD机考-找座位-逻辑分析(JAVA 2025B卷)
java·开发语言·华为od
快乐肚皮1 小时前
Java的Arrays.sort():排序算法与优化分析
java·排序算法·归并排序·快速排序
西洼工作室1 小时前
Spring Boot常用依赖大全:从入门到精通
java·spring boot·后端
Hanson Huang2 小时前
【Spring AI 1.0.0】Spring AI 1.0.0框架快速入门(2)——Prompt(提示词)
java·人工智能·spring·spring ai
加油冲丫2 小时前
Java过滤器的基本概念
java·开发语言·后端·servlet
4060ti2 小时前
gradle 入门
java·gradle