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

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

相关推荐
Dola_Pan27 分钟前
Linux文件IO(二)-文件操作使用详解
java·linux·服务器
wang_book30 分钟前
Gitlab学习(007 gitlab项目操作)
java·运维·git·学习·spring·gitlab
蜗牛^^O^1 小时前
Docker和K8S
java·docker·kubernetes
从心归零2 小时前
sshj使用代理连接服务器
java·服务器·sshj
一个诺诺前行的后端程序员2 小时前
springcloud微服务实战<1>
spring·spring cloud·微服务
IT毕设梦工厂3 小时前
计算机毕业设计选题推荐-在线拍卖系统-Java/Python项目实战
java·spring boot·python·django·毕业设计·源码·课程设计
Ylucius4 小时前
动态语言? 静态语言? ------区别何在?java,js,c,c++,python分给是静态or动态语言?
java·c语言·javascript·c++·python·学习
七夜zippoe4 小时前
分布式系统实战经验
java·分布式
是梦终空4 小时前
JAVA毕业设计176—基于Java+Springboot+vue3的交通旅游订票管理系统(源代码+数据库)
java·spring boot·vue·毕业设计·课程设计·源代码·交通订票
落落落sss4 小时前
sharding-jdbc分库分表
android·java·开发语言·数据库·servlet·oracle