• springboot+mybatisplus+druid多数据源


    springboot+mybatisplus+druid多数据源

    参考文章:

    https://blog.csdn.net/pyd950812/article/details/102516132?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.edu_weight&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.edu_weight

    1. yml

      spring:
        # 数据源配置
        datasource:
          master:
            username: root
            password: 12345678
            url: jdbc:p6spy:mysql://ip:3306/cws-dev?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf8
            #mysql8版本以上驱动包指定新的驱动类
            #driver-class-name: com.mysql.cj.jdbc.Driver
            driver-class-name: com.p6spy.engine.spy.P6SpyDriver
            #   数据源其他配置, 在 DruidConfig配置类中手动绑定
            initialSize: 8
            minIdle: 5
            maxActive: 20
            maxWait: 60000
            timeBetweenEvictionRunsMillis: 60000
            minEvictableIdleTimeMillis: 300000
            validationQuery: SELECT 1
          slave:
            username: root
            password: cws123456
            url: jdbc:p6spy:mysql://ip:3306/cws?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf8
            #mysql8版本以上驱动包指定新的驱动类      #driver-class-name: com.mysql.cj.jdbc.Driver
            driver-class-name: com.p6spy.engine.spy.P6SpyDriver
            #   数据源其他配置, 在 DruidConfig配置类中手动绑定
            initialSize: 8
            minIdle: 5
            maxActive: 20
            maxWait: 60000
            timeBetweenEvictionRunsMillis: 60000
            minEvictableIdleTimeMillis: 300000
            validationQuery: SELECT 12
      
    2. DatabaseType

      public enum DatabaseType {
          dataBase1,
          dataBase2
      }
      
    3. DatabaseContextHoder

      public class DatabaseContextHolder {
      
          private static final ThreadLocal<DatabaseType> contextHolder = new ThreadLocal<>();
      
          public static void setDatabaseType(DatabaseType type) {
              contextHolder.set(type);
          }
      
          public static DatabaseType getDatabaseType() {
              return contextHolder.get();
          }
      }
      
    4. DruidConfg

      @Configuration
      public class DruidConfig {
      
        @ConfigurationProperties(prefix = "spring.datasource.master")
        @Bean(name = "masterDataSource")
        public DataSource masterDataSource() {
          return new DruidDataSource();
        }
      
        @ConfigurationProperties(prefix = "spring.datasource.slave")
        @Bean(name = "slaveDataSource")
        public DataSource slaveDataSource() {
          return new DruidDataSource();
        }
      }
      
    5. DynamicDAtaSource

      public class DynamicDataSource extends AbstractRoutingDataSource {
      
        @Override
        protected Object determineCurrentLookupKey() {
          // 使用DatabaseContextHolder获取当前线程的DatabaseType
          return DatabaseContextHolder.getDatabaseType();
        }
      }
      
    6. MybatisPlusConfig

      @EnableTransactionManagement
      @MapperScan("com.vivo.cws.web.mapper")
      @Configuration
      public class MybatisPlusConfig {
        /** 分页插件 */
        @Bean
        public PaginationInterceptor paginationInterceptor() {
          return new PaginationInterceptor();
        }
      
        /**
         * Primary 该注解表示在同一个接口有多个实现类可以注入的时候,默认选择哪一个,而不是让@autowire注解报错 Qualifier
         * 根据名称进行注入,通常是在具有相同的多个类型的实例的一个注入(例如有多个DataSource类型的实例)
         */
        @Bean
        @Primary
        public DynamicDataSource dataSource(
            @Qualifier("masterDataSource") DataSource masterDataSource,
            @Qualifier("slaveDataSource") DataSource slaveDataSource) {
          Map<Object, Object> targetDataSources = new HashMap<>();
          targetDataSources.put(DatabaseType.dataBase1, masterDataSource);
          targetDataSources.put(DatabaseType.dataBase2, slaveDataSource);
          DynamicDataSource dataSource = new DynamicDataSource();
          // 该方法是AbstractRoutingDataSource的方法
          dataSource.setTargetDataSources(targetDataSources);
          // 默认的datasource设置为myTestDbDataSource
          dataSource.setDefaultTargetDataSource(masterDataSource);
          return dataSource;
        }
      
        @Bean
        public SqlSessionFactory sqlSessionFactory(
            @Qualifier("masterDataSource") DataSource masterDataSource,
            @Qualifier("slaveDataSource") DataSource slaveDataSource)
            throws Exception {
          MybatisSqlSessionFactoryBean mybatisSqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();
          mybatisSqlSessionFactoryBean.setDataSource(this.dataSource(masterDataSource, slaveDataSource));
          return mybatisSqlSessionFactoryBean.getObject();
        }
      }
      
    7. 测试

      @GetMapping("")
      public String test() {
        List<SysRole> list = sysRoleService.list();
        for (SysRole sysRole : list) {
          System.out.println(sysRole);
        }
        System.out.println("-------");
      
        DatabaseContextHolder.setDatabaseType(DatabaseType.dataBase2);
        List<SysRole> list2 = sysRoleService.list();
        for (SysRole sysRole : list2) {
          System.out.println(sysRole);
        }
        System.out.println("-------");
        return "success";
      }
      
  • 相关阅读:
    java多线程--定时器Timer的使用
    java多线程--线程池的使用
    java多线程--多线程基础小结
    java基础--java.util.Date类型小结
    onClickRow 事件
    C#里的SubString和Convert.ToDateTime
    jquery+easyui开发、培训文档
    Jquery函数大全
    前端最全的 API 集锦
    17个CSS知识点整理
  • 原文地址:https://www.cnblogs.com/proper128/p/13984314.html
Copyright © 2020-2023  润新知