spring boot +MybatisPlus+MySQL配置多数据源及根据包路径进行数据源切换

  • 1、设置配置文件
  • 2、新增动态数据源类
  • 3、数据源枚举类
  • 4、修改MybatisPlus配置类
  • 5、数据源切换类
  • 6、AOP切面根据请求访问包路径切换数据源​​​​​

     

    1、设置配置文件

    spring boot 多数据源及线程池配置

    	spring:
    	 datasource:
    	    dynamic:
    	      druid: # 全局druid参数,绝大部分值和默认保持一致。(现已支持的参数如下,不清楚含义不要乱设置)
    	        # 连接池的配置信息
    	        # 初始化大小,最小,最大
    	        initial-size: 5
    	        min-idle: 5
    	        maxActive: 20
    	        # 配置获取连接等待超时的时间
    	        maxWait: 60000
    	        # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
    	        timeBetweenEvictionRunsMillis: 60000
    	        # 配置一个连接在池中最小生存的时间,单位是毫秒
    	        minEvictableIdleTimeMillis: 300000
    	        validationQuery: SELECT 1 FROM DUAL
    	        testWhileIdle: true
    	        testOnBorrow: false
    	        testOnReturn: false
    	        # 打开PSCache,并且指定每个连接上PSCache的大小
    	        poolPreparedStatements: true
    	        maxPoolPreparedStatementPerConnectionSize: 20
    	        # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
    	        filters: stat,wall,slf4j
    	        # 通过connectProperties属性来打开mergeSql功能;慢SQL记录
    	        connectionProperties: druid.stat.mergeSql\=true;druid.stat.slowSqlMillis\=5000
    	      datasource:
    	        master:
    	          url: jdbc:mysql://ip/db?characterEncoding=UTF-8&useUnicode=true&useSSL=false
    	          username: username
    	          password: password
    	          driver-class-name: com.mysql.jdbc.Driver
    	        gateway-datasource:
    	          url: jdbc:mysql://ip/db?useUnicode=true&characterEncoding=utf8&autoReconnect=true&zeroDateTimeBehavior=convertToNull&transformedBitIsBoolean=true
    	          username: username
    	          password: password
    	          driver-class-name: com.mysql.jdbc.Driver
    	          
    	      mybatis-plus:
    			  mapper-locations: classpath*:org/*/*/**/xml/*Mapper.xml
    
    
  • 2、新增动态数据源类

    public class DynamicDataSource extends AbstractRoutingDataSource {
        @Override
        protected Object determineCurrentLookupKey() {
            String aa = DataSourceContextHolder.getDbType();
            return DataSourceContextHolder.getDbType();
        }
    }
    
  • 3、数据源枚举类

    public enum DBTypeEnum {
    
        dataSourceCms("dataSourceCms"), dataSourceGateway("dataSourceGateway");
        private String value;
    
        DBTypeEnum(String value) {
            this.value = value;
        }
    
        public String getValue() {
            return value;
        }
    }
    
  • 4、修改MybatisPlus配置类

    MybatisPlus配置类

    
    @Configuration
    @MapperScan(value={"org.*.*.**.mapper*"})//指定对应的mapper路径
    public class MybatisPlusConfig {
    
        /**
             *  分页插件
         */
        @Bean
        public PaginationInterceptor paginationInterceptor() {
            return new PaginationInterceptor().setLimit(-1);
        }
    
        @Bean(name = "dataSourceCms")
        @ConfigurationProperties(prefix = "spring.datasource.dynamic.datasource.master")
        public DataSource primaryDataSource(){
            return new DruidDataSource();
        }
        @Bean(name = "dataSourceGateway")
        @ConfigurationProperties(prefix = "spring.datasource.dynamic.datasource.gateway-datasource")
        public DataSource localDataSource(){
            return new DruidDataSource();
        }
    
        /**
         * 动态数据源配置
         * @return
         */
        @Bean
        @Primary
        public DataSource multipleDataSource (@Qualifier("dataSourceCms") DataSource dataSourceCms,
                                              @Qualifier("dataSourceGateway") DataSource dataSourceGateway ) {
            DynamicDataSource dynamicDataSource = new DynamicDataSource();
            Map< Object, Object > targetDataSources = new HashMap<>();
            targetDataSources.put(DBTypeEnum.dataSourceCms.getValue(), dataSourceCms );
            targetDataSources.put(DBTypeEnum.dataSourceGateway.getValue(), dataSourceGateway);
            dynamicDataSource.setTargetDataSources(targetDataSources);
            dynamicDataSource.setDefaultTargetDataSource(dataSourceCms);
            return dynamicDataSource;
        }
    
        @Bean("sqlSessionFactory")
        public SqlSessionFactory sqlSessionFactory() throws Exception {
            MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean();
            sqlSessionFactory.setDataSource(multipleDataSource(primaryDataSource(),localDataSource()));
            sqlSessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:org/jeecg/modules/**/xml/*Mapper.xml"));
    
            MybatisConfiguration configuration = new MybatisConfiguration();
            //configuration.setDefaultScriptingLanguage(MybatisXMLLanguageDriver.class);
    //        configuration.setJdbcTypeForNull(JdbcType.NULL);
            configuration.setMapUnderscoreToCamelCase(true);
            configuration.setCacheEnabled(false);
            sqlSessionFactory.setConfiguration(configuration);
            sqlSessionFactory.setPlugins(new Interceptor[]{ //PerformanceInterceptor(),OptimisticLockerInterceptor()
                    paginationInterceptor() //添加分页功能
            });
    
            return sqlSessionFactory.getObject();
        }
    }
    
  • 5、数据源切换类

    public class DataSourceContextHolder {
        private static final ThreadLocal contextHolder = new ThreadLocal<>(); //实际上就是开启多个线程,每个线程进行初始化一个数据源
        /**
         * 设置数据源
         * @param dbTypeEnum
         */
        public static void setDbType(DBTypeEnum dbTypeEnum) {
            contextHolder.set(dbTypeEnum.getValue());
        }
    
        /**
         * 取得当前数据源
         * @return
         */
        public static String getDbType() {
            return (String) contextHolder.get();
        }
    
        /**
         * 清除上下文数据
         */
        public static void clearDbType() {
            contextHolder.remove();
        }
    }
    
  • 6、AOP切面根据请求访问包路径切换数据源

    @Aspect
    @Component
    public class DataBaseAspect {
    
    //    @Pointcut("@annotation(org.jeecg.config.database.DataBase)")
    
        /**
         * 使用第一个数据源的路径
         */
        @Pointcut("execution(* org.*.*.system.service.impl..*.*(..))" +
                "||execution(* org.*.*.quartz.service.impl..*.*(..)) "
             )
        public void dbPointCut() {
    
        }
    
        /**
         * 使用第二个数据源的路径
         */
        @Pointcut("execution(* org.*.*.gateway..*.*(..))")
        public void dbPointCut2() {
    
        }
    
        @Before("dbPointCut()")
        public void beforeSwitchDS(JoinPoint point) {
            DataSourceContextHolder.setDbType(DBTypeEnum.dataSourceCms);
        }
    
        @Before("dbPointCut2()")
        public void change2(JoinPoint point) {
            DataSourceContextHolder.setDbType(DBTypeEnum.dataSourceGateway);
        }
    
        @After("dbPointCut()")
        public void afterSwitchDS(JoinPoint point) {
            DataSourceContextHolder.clearDbType();
        }
    }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值