原文: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

Spring Boot配置多数据源并实现Druid自动切换的更多相关文章

  1. 如何通过Spring Boot配置动态数据源访问多个数据库

    之前写过一篇博客<Spring+Mybatis+Mysql搭建分布式数据库访问框架>描述如何通过Spring+Mybatis配置动态数据源访问多个数据库.但是之前的方案有一些限制(原博客中 ...

  2. spring boot:配置shardingsphere(sharding jdbc)使用druid数据源(druid 1.1.23 / sharding-jdbc 4.1.1 / mybatis / spring boot 2.3.3)

    一,为什么要使用druid数据源? 1,druid的优点 Druid是阿里巴巴开发的号称为监控而生的数据库连接池 它的优点包括: 可以监控数据库访问性能 SQL执行日志 SQL防火墙 但spring ...

  3. spring boot 配置双数据源mysql、sqlServer

    背景:原来一直都是使用mysql数据库,在application.properties 中配置数据库信息 spring.datasource.url=jdbc:mysql://xxxx/test sp ...

  4. spring boot 配置多数据源

    https://www.jianshu.com/p/b2e53a2521fc

  5. Spring boot配置多个Redis数据源操作实例

    原文:https://www.jianshu.com/p/c79b65b253fa Spring boot配置多个Redis数据源操作实例 在SpringBoot是项目中整合了两个Redis的操作实例 ...

  6. spring boot配置druid连接池连接mysql

    Spring Boot 集成教程 Spring Boot 介绍 Spring Boot 开发环境搭建(Eclipse) Spring Boot Hello World (restful接口)例子 sp ...

  7. Spring Boot与多数据源那点事儿~

    持续原创输出,点击上方蓝字关注我 目录 前言 写这篇文章的目的 什么是多数据源? 何时用到多数据源? 整合单一的数据源 整合Mybatis 多数据源如何整合? 什么是动态数据源? 数据源切换如何保证线 ...

  8. 一文读懂Spring动态配置多数据源---源码详细分析

    Spring动态多数据源源码分析及解读 一.为什么要研究Spring动态多数据源 ​ 期初,最开始的原因是:想将答题服务中发送主观题答题数据给批改中间件这块抽象出来, 但这块主要使用的是mq消息的方式 ...

  9. spring boot配置mybatis和事务管理

    spring boot配置mybatis和事务管理 一.spring boot与mybatis的配置 1.首先,spring boot 配置mybatis需要的全部依赖如下: <!-- Spri ...

随机推荐

  1. Cas(04)——更改认证方式

    在Cas Server的WEB-INF目录下有一个deployerConfigContext.xml文件,该文件是基于Spring的配置文件,里面存放的内容常常是部署人员需要修改的内容.其中认证方式也 ...

  2. Data - 数据思维 - 下篇

    9 - 数据解读与表达 数据解读 数据解读需要选择一个基点.一个参照系,单独的一个数值往往不具备价值,它只是数字. 注意点: 关注异常值,并深究WHY? 相互验证.大胆假设.多方验证. 把握趋势或者规 ...

  3. 2019年Java面试题基础系列228道(4)

    1.Java 中能创建 volatile 数组吗? 能,Java 中可以创建 volatile 类型数组,不过只是一个指向数组的引用,而不是整个数组.我的意思是,如果改变引用指向的数组,将会受到 vo ...

  4. html收尾

    <form>input 元素</form> <fieldset ></fieldset > <legend ></legend> ...

  5. Python标准库: functools (cmp_to_key, lru_cache, total_ordering, partial, partialmethod, reduce, singledispatch, update_wrapper, wraps)

    functools模块处理的对象都是其他的函数,任何可调用对象都可以被视为用于此模块的函数. 1. functools.cmp_to_key(func) 因为Python3不支持比较函数,cmp_to ...

  6. LeetCode 590. N叉树的后序遍历(N-ary Tree Postorder Traversal)

    590. N叉树的后序遍历 590. N-ary Tree Postorder Traversal 题目描述 给定一个 N 叉树,返回其节点值的后序遍历. LeetCode590. N-ary Tre ...

  7. TensorSpace:超酷炫3D神经网络可视化框架

    TensorSpace:超酷炫3D神经网络可视化框架 TensorSpace - 一款 3D 模型可视化框架,支持多种模型,帮助你可视化层间输出,更直观地展示模型的输入输出,帮助理解模型结构和输出方法 ...

  8. [SVN] - 使用 TortoiseSVN 进行文件比对非常慢 之 解决

    背景 Windows 10 + TortoiseSVN-v1.9.7使用默认的 TortoiseMerge 进行文件比对,打开速度非常非常慢. 解决 禁用 TortoiseMerge / Settin ...

  9. PAT(B) 1029 旧键盘(Java)字符串

    题目链接:1029 旧键盘 (20 point(s)) 题目描述 旧键盘上坏了几个键,于是在敲一段文字的时候,对应的字符就不会出现.现在给出应该输入的一段文字.以及实际被输入的文字,请你列出肯定坏掉的 ...

  10. 【并发】7、借助redis 实现多线程生产消费队列

    1.这是第一个简单的初始化版本,看起来比使用fqueue似乎更好用 package queue.redisQueue; import queue.fqueue.vo.TempVo; import re ...