• Spring Boot配置多数据源并实现Druid自动切换


    原文:https://blog.csdn.net/acquaintanceship/article/details/75350653

    Spring Boot配置多数据源
    配置yml文件
    主数据源配置
    从数据源配置
    使用dao
    日志
    Spring Boot配置多数据源
    配置yml文件
    这里并没有对spring.datasource配置数据源,因为增加新数据源后,系统会覆盖由spring.datasource自动配置的内容。
    这里自定义了两个数据源spring.datasource.cmmi和spring.datasource.zentao

    spring:
      datasource:
        type: com.alibaba.druid.pool.DruidDataSource
        base:
          type: com.alibaba.druid.pool.DruidDataSource
          driver-class-name: com.mysql.cj.jdbc.Driver
          initialize: true #指定初始化数据源,是否用data.sql来初始化,默认: true
          name: cmmi
          url: jdbc:mysql://127.0.0.1:3306/cmmi?useUnicode=true&characterEncoding=utf-8&useSSL=false&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC&zeroDateTimeBehavior=convertToNull
          username: root
          password: root
        zentao:
          type: com.alibaba.druid.pool.DruidDataSource
          driver-class-name: com.mysql.cj.jdbc.Driver
          initialize: true
          name: zentaopro
          url: jdbc:mysql://127.0.0.1:3306/zentaopro?useUnicode=true&characterEncoding=utf-8&useSSL=false&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC&zeroDateTimeBehavior=convertToNull
          username: root
          password: root

    主数据源配置
    注意,配置类需要对DataSource、DataSourceTransactionManager、SqlSessionFactory 、SqlSessionTemplate四个数据项进行配置;DataSource类型需要引入javax.sql.DataSource;当系统中有多个数据源时,必须有一个数据源为主数据源,使用@Primary修饰。
    @MapperScan对指定dao包建立映射,确保在多个数据源下,自动选择合适的数据源,而在service层里不需要做特殊说明。

    @Configuration
    @MapperScan(basePackages = "cmmi.dao.base", sqlSessionTemplateRef = "baseSqlSessionTemplate")
    public class BaseDataSourceConfig {
        @Bean(name = "baseDataSource")
        @ConfigurationProperties(prefix = "spring.datasource.base")
        @Primary
        public DataSource setDataSource() {
            return DataSourceBuilder.create().build();
        }
    
        @Bean(name = "baseTransactionManager")
        @Primary
        public DataSourceTransactionManager setTransactionManager(@Qualifier("baseDataSource") DataSource dataSource) {
            return new DruidDataSource();
        }
    
        @Bean(name = "baseSqlSessionFactory")
        @Primary
        public SqlSessionFactory setSqlSessionFactory(@Qualifier("baseDataSource") DataSource dataSource) throws Exception {
            SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
            bean.setDataSource(dataSource);
            bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/base/*.xml"));
            return bean.getObject();
        }
    
        @Bean(name = "baseSqlSessionTemplate")
        @Primary
        public SqlSessionTemplate setSqlSessionTemplate(@Qualifier("baseSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
            return new SqlSessionTemplate(sqlSessionFactory);
        }
    }

    从数据源配置

    @Configuration
    @MapperScan(basePackages = "cmmi.dao.zentao", sqlSessionTemplateRef = "zentaoSqlSessionTemplate")
    public class ZentaoDataSourceConfig {
        @Bean(name = "zentaoDataSource")
        @ConfigurationProperties(prefix = "spring.datasource.zentao")
        public DataSource setDataSource() {
            return new DruidDataSource();
        }
    
        @Bean(name = "zentaoTransactionManager")
        public DataSourceTransactionManager setTransactionManager(@Qualifier("zentaoDataSource") DataSource dataSource) {
            return new DataSourceTransactionManager(dataSource);
        }
    
        @Bean(name = "zentaoSqlSessionFactory")
        public SqlSessionFactory setSqlSessionFactory(@Qualifier("zentaoDataSource") DataSource dataSource) throws Exception {
            SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
            bean.setDataSource(dataSource);
            bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/zentao/*.xml"));
            return bean.getObject();
        }
    
        @Bean(name = "zentaoSqlSessionTemplate")
        public SqlSessionTemplate setSqlSessionTemplate(@Qualifier("zentaoSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
            return new SqlSessionTemplate(sqlSessionFactory);
        }
    }

    使用dao

    这里只需要正常使用dao就可以了,spring会根据数据源配置的映射自动选择相应数据源,而不需要在service做特殊说明。

    @Service
    public class TestService {
        private final ZtUserMapper ztUserMapper;
        private final LevelDic levelDic;
    
        @Autowired
        public TestService(ZtUserMapper ztUserMapper, LevelDic levelDic) {
            this.ztUserMapper = ztUserMapper;
            this.levelDic = levelDic;
        }
    
        public void test() {
            ztUserMapper.selectByPrimaryKey(1);
            levelDic.setDicId(new Integer(1).byteValue());
        }
    }

    日志

    o.a.c.c.C.[Tomcat].[localhost].[/cmmi] : Initializing Spring FrameworkServlet ‘dispatcherServlet’ 
    o.s.web.servlet.DispatcherServlet : FrameworkServlet ‘dispatcherServlet’: initialization started 
    o.s.web.servlet.DispatcherServlet : FrameworkServlet ‘dispatcherServlet’: initialization completed in 23 ms 
    com.alibaba.druid.pool.DruidDataSource : {dataSource-1,cmmi} inited 
    com.alibaba.druid.pool.DruidDataSource : {dataSource-2,zentaopro} inited
  • 相关阅读:
    [支付]银联支付(对jdk有要求,最好直接使用jdk7)
    [支付]支付宝支付(网银在线支付)
    Eclipse编辑窗口放大缩小的快捷键
    jQuery Validation Engine 表单验证
    Eclipse能否把选中的一段代码向前或向后缩进一个tab的位
    hql查询技巧
    Web桌面端
    大型网站技术架构
    FastDFS--分布式文件系统
    消息队列
  • 原文地址:https://www.cnblogs.com/shihaiming/p/11063092.html
Copyright © 2020-2023  润新知