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

摘要:
useUnicode=true&characterEncoding=utf-8&useSSL=false&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC&zeroDateTimeBehavior=convertToNullusername:rootpassword:root主数据源配置注意,配置类需要对DataSource、DataSourceTransactionManager、SqlSessionFactory、SqlSessionTemplate四个数据项进行配置;DataSource类型需要引入javax.sql.DataSource;当系统中有多个数据源时,必须有一个数据源为主数据源,使用@Primary修饰。@MapperScan对指定dao包建立映射,确保在多个数据源下,自动选择合适的数据源,而在service层里不需要做特殊说明。

原文: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 classBaseDataSourceConfig {
    @Bean(name = "baseDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.base")
    @Primary
    publicDataSource setDataSource() {
        returnDataSourceBuilder.create().build();
    }
    @Bean(name = "baseTransactionManager")
    @Primary
    public DataSourceTransactionManager setTransactionManager(@Qualifier("baseDataSource") DataSource dataSource) {
        return newDruidDataSource();
    }
    @Bean(name = "baseSqlSessionFactory")
    @Primary
    public SqlSessionFactory setSqlSessionFactory(@Qualifier("baseDataSource") DataSource dataSource) throwsException {
        SqlSessionFactoryBean bean = newSqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/base/*.xml"));
        returnbean.getObject();
    }
    @Bean(name = "baseSqlSessionTemplate")
    @Primary
    public SqlSessionTemplate setSqlSessionTemplate(@Qualifier("baseSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throwsException {
        return newSqlSessionTemplate(sqlSessionFactory);
    }
}

从数据源配置

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

使用dao

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

@Service
public classTestService {
    private finalZtUserMapper ztUserMapper;
    private finalLevelDic levelDic;
    @Autowired
    publicTestService(ZtUserMapper ztUserMapper, LevelDic levelDic) {
        this.ztUserMapper =ztUserMapper;
        this.levelDic =levelDic;
    }
    public voidtest() {
        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 23ms 
com.alibaba.druid.pool.DruidDataSource : {dataSource-1,cmmi} inited 
com.alibaba.druid.pool.DruidDataSource : {dataSource-2,zentaopro} inited

免责声明:文章转载自《Spring Boot配置多数据源并实现Druid自动切换》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇时序数据库的选择?关于function pg_switch_xlog() does not exist下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

springmvc常用注解标签详解【转】

转载自:http://www.cnblogs.com/leskang/p/5445698.html 1、@Controller 在SpringMVC 中,控制器Controller 负责处理由DispatcherServlet 分发的请求,它把用户请求的数据经过业务处理层处理之后封装成一个Model ,然后再把该Model 返回给对应的View 进行展示。...

spring+cxf 开发webService(主要是记录遇到spring bean注入不进来的解决方法)

这里不介绍原理,只是记录自己spring+cxf的开发过程和遇到的问题 场景:第三方公司需要调用我们的业务系统,以xml报文的形式传递数据,之后我们解析报文存储到我们数据库生成业务单据; WebService的框架由多种,这里选cxf,与Spring的集成比较好; 直接看代码 1项目用的maven,首先添加依赖(这个依赖啊 ,教程引用几个的都有,这个看需要...

SpringBoot启动过程中涉及到了扩展接口

SpringApplicationRunListener接口 1、ApplicationListener接口 是ApplicationContext的事件监听器 2、EnvironmentPostProcessor接口 上下文环境后置处理器,事件中调用 3、PropertySourceLoader接口 自定义配置文件加载器,自己解析配置文件属性...

Spring整合多数据源实现动态切换

在实际项目中时常需要连接多个数据库,而且不同的业务需求在实现过程当中往往需要访问不同的数据库。 jdbc.properties配置文件,配置多个dataSource ##########################MySQL##################################### hibernate.dialect=org.hiber...

三种方式创建bean对象在springIOC容器中初始化、销毁阶段要调用的自定义方法

1. 使用@Bean注解定义initMethod和destroyMethod 所谓initMethod和destroyMethod,是指在springIOC容器中,对于bean对象执行到初始化阶段和销毁阶段所调用的方法,其并不是初始化方法和销毁方法本身。 对于单例模式,initMethod会在创建容器时,构造方法、属性赋值方法完成之后调用,destroyM...

Druid 架构

本篇译自 Druid项目白皮书部分内容( https://github.com/apache/incubator-druid/tree/master/publications/whitepaper/druid.pdf),如果有兴趣可看细看原pdf【初次翻译多多包涵】 一个 Druid 集群包含多种特定功能的节点, 我们相信这种设计能够分散业务并且简化整个系...