springboot多数据源配置

项目配置

多数据源配置主要用到spring的AbstractRoutingDataSource,网上介绍资料也有很多,这里主要做个备份

maven依赖

除了数据库连接的依赖,spring的依赖,Mybatis的依赖之外还需要


    com.alibaba
    druid-spring-boot-starter
    1.1.5

使用com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder生成DataSource

数据源配置

  1. application.properties

    #mysql
    multiple.datasource.mysql0.driver-class-name=com.mysql.jdbc.Driver
    multiple.datasource.mysql0.url=jdbc:mysql://mysql.a15223331219-mysql.svc.bja.ipaas.cn:8066/?useUnicode=true&characterEncoding=utf-8&autoReconnect=true
    multiple.datasource.mysql0.username=proxy
    multiple.datasource.mysql0.password=proxy.ibk
    #sqlserver
    multiple.datasource.sqlserver0.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver
    multiple.datasource.sqlserver0.url=jdbc:sqlserver://***:1433;
    multiple.datasource.sqlserver0.username=**
    multiple.datasource.sqlserver0.password=***
    # 以下多个数据源
    ....
    
  2. 为了方便管理多数据源,我们使用枚举类进行管理

    public enum DataSourceKey {
    	MYSQL0(),
    	SQLSERVER0(),
    	;
    }
    
  3. 创建数据源Bean

    @Configuration
    public class DynamicDataSourceConfiguration {
        @Bean
        @ConfigurationProperties(prefix = "multiple.datasource.mysql0")
        public DataSource mysql0() {
            return DruidDataSourceBuilder.create().build();
        }
    
        @Bean
        @ConfigurationProperties(prefix = "multiple.datasource.sqlserver0")
        public DataSource sqlserver0() {
            return DruidDataSourceBuilder.create().build();
        }
    
       /**
         * 核心动态数据源
         *
         * @return 数据源实例
         */
        @Bean
        public DataSource dynamicDataSource() {
        	// 设置默认数据源为mysql0
            DynamicRoutingDataSource dataSource = new DynamicRoutingDataSource();
            dataSource.setDefaultTargetDataSource(mysql0());
            
            Map<Object, Object> dataSourceMap = new HashMap<>(2);
            dataSourceMap.put(DataSourceKey.MYSQL0, mysql0());
            dataSourceMap.put(DataSourceKey.SQLSERVER0, sqlserver0());
            // AbstractRoutingDataSource.setTargetDataSources
            dataSource.setTargetDataSources(dataSourceMap);
            return dataSource;
        }
    
        @Bean
        public SqlSessionFactory sqlSessionFactory() throws Exception {
            SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
            sqlSessionFactoryBean.setDataSource(dynamicDataSource());
            sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml"));
            return sqlSessionFactoryBean.getObject();
        }
        
        @Bean
        public SqlSessionTemplate sqlSessionTemplate() throws Exception {
            return new SqlSessionTemplate(sqlSessionFactory());
        }
    
        /**
         * 事务管理
         *
         * @return 事务管理实例
         */
        @Bean
        public PlatformTransactionManager platformTransactionManager() {
            return new DataSourceTransactionManager(dynamicDataSource());
        }
    }
    
    此类将多数据源注册到spring容器,且注册到AbstractRoutingDataSource中
    创建sql会话工厂
  4. 创建多数据源上下文切换类

    public class DynamicDataSourceContextHolder {
    
        private static final ThreadLocal<DataSourceKey> CURR_DATA_SOURCE = new ThreadLocal<>();
    
        /**
         * 清除当前数据源
         */
        public static void clear() {
            CURR_DATA_SOURCE.remove();
        }
    
        /**
         * 获取当前使用的数据源
         *
         * @return 当前使用数据源的ID
         */
        public static DataSourceKey get() {
            return CURR_DATA_SOURCE.get();
        }
    
        /**
         * 设置当前使用的数据源
         *
         * @param value 需要设置的数据源ID
         */
        public static void set(DataSourceKey value) {
            CURR_DATA_SOURCE.set(value);
        }
    }
    
  5. AbstractRoutingDataSource

    public class DynamicRoutingDataSource extends AbstractRoutingDataSource {
        @Override
        protected Object determineCurrentLookupKey() {
            return DynamicDataSourceContextHolder.get();
        }
    }
    

    以上为多数据源配置。在使用时,只需要DynamicDataSourceContextHolder.set(DataSourceKey.MYSQL0);即可实时切换数据源。

你可能感兴趣的:(spring,boot)