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 and C5 小时前
MyBatisPlus
java
秋野酱5 小时前
如何在 Spring Boot 中实现自定义属性
java·数据库·spring boot
安的列斯凯奇6 小时前
SpringBoot篇 单元测试 理论篇
spring boot·后端·单元测试
Bunny02126 小时前
SpringMVC笔记
java·redis·笔记
blammmp6 小时前
Java EE 进阶:Spring MVC(1)
spring·java-ee·mvc
feng_blog66886 小时前
【docker-1】快速入门docker
java·docker·eureka
枫叶落雨2228 小时前
04JavaWeb——Maven-SpringBootWeb入门
java·maven
m0_748232398 小时前
SpringMVC新版本踩坑[已解决]
java
多则惑少则明8 小时前
SSM开发(一)JAVA,javaEE,spring,springmvc,springboot,SSM,SSH等几个概念区别
spring boot·spring·ssh
码农小灰8 小时前
Spring MVC中HandlerInterceptor和Filter的区别
java·spring·mvc