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
Spring Boot配置多数据源并实现Druid自动切换的更多相关文章
- 如何通过Spring Boot配置动态数据源访问多个数据库
之前写过一篇博客<Spring+Mybatis+Mysql搭建分布式数据库访问框架>描述如何通过Spring+Mybatis配置动态数据源访问多个数据库.但是之前的方案有一些限制(原博客中 ...
- 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 ...
- spring boot 配置双数据源mysql、sqlServer
背景:原来一直都是使用mysql数据库,在application.properties 中配置数据库信息 spring.datasource.url=jdbc:mysql://xxxx/test sp ...
- spring boot 配置多数据源
https://www.jianshu.com/p/b2e53a2521fc
- Spring boot配置多个Redis数据源操作实例
原文:https://www.jianshu.com/p/c79b65b253fa Spring boot配置多个Redis数据源操作实例 在SpringBoot是项目中整合了两个Redis的操作实例 ...
- spring boot配置druid连接池连接mysql
Spring Boot 集成教程 Spring Boot 介绍 Spring Boot 开发环境搭建(Eclipse) Spring Boot Hello World (restful接口)例子 sp ...
- Spring Boot与多数据源那点事儿~
持续原创输出,点击上方蓝字关注我 目录 前言 写这篇文章的目的 什么是多数据源? 何时用到多数据源? 整合单一的数据源 整合Mybatis 多数据源如何整合? 什么是动态数据源? 数据源切换如何保证线 ...
- 一文读懂Spring动态配置多数据源---源码详细分析
Spring动态多数据源源码分析及解读 一.为什么要研究Spring动态多数据源 期初,最开始的原因是:想将答题服务中发送主观题答题数据给批改中间件这块抽象出来, 但这块主要使用的是mq消息的方式 ...
- spring boot配置mybatis和事务管理
spring boot配置mybatis和事务管理 一.spring boot与mybatis的配置 1.首先,spring boot 配置mybatis需要的全部依赖如下: <!-- Spri ...
随机推荐
- 常见的SQL注入检测语句(转载)
0x00 前言 现在很多WAF都能拦截sqlmap.havij 等注入工具的发包注入,所以这时我们需要在浏览器上使用hackerbar 进行手工注入,或者说是手工绕过注入攻击 0x01 发现SQL 注 ...
- 基于python的App UI自动化环境搭建
Android端Ui 自动化环境搭建 一,安装JDK.SDK 二,添加环境变量 Widows:1.系统变量→新建 JAVA_HOME 变量E:\Java\jdk1.7.0 jdk安装目录 2.系统变量 ...
- Ajax基本概念
一. Ajax 1. 什么是ajax Ajax: asynchronous javascript and xml (异步js和xml) 其是可以与服务器进行(异步/同步)交互的技术一. ajax ...
- CentOS 安装tab命令补全
CentOS 安装tab命令补全 1. 安装epel 源 yum -y install epel-release 2. 加快yum速度 yum -y install yum-plugin-fastes ...
- 虚拟机性能监控与故障处理工具(深入理解java虚拟机三)
JDK自带的工具可以方便的帮助我们处理一些问题,包括查看JVM参数,分析内存变化,查看内存区域,查看线程等信息. 我们熟悉的有java.exe,javac.exe,javap.exe(偶尔用),jps ...
- Python19之函数和过程
一.函数和过程 函数和过程都是指一段实现特定功能的代码段,如果该代码段有返回值则称为函数,否则称为过程. 注:Python中只有函数而没有过程,就算是函数体内没有return语句返回一个值,Pytho ...
- 织梦/dedecms采集怎么去除a标签
dedecms采集去除a标签代码 DedeCMS采集规则-过滤-替换-技巧2009-01-14 15:491.采集去除链接[Copy to clipboard]CODE:{dede:trim}]*)& ...
- oracle如何保证数据一致性和避免脏读
oracle通过undo保证一致性读和不发生脏读 1.不发生脏读2.一致性读3. 事务槽(ITL)小解 1.不发生脏读 例如:用户A对表更新了,没有提交,用户B对进行查询,没有提交的更新不能出现在 ...
- Missing android.support.FILE_PROVIDER_PATHS meta-data 报错原因分析
此类错误多半因为拼写错误导致.有StackOverflow上便有网友将"FILE_PROVIDER_PATHS"误写成"FILE_PROVIDE_PATHS"的 ...
- pyrhon 第一个小购物车例子
product_list=[[],[],[],[]] shopping_list=[] salary = input("请输入你的工资:") if salary.isdigit() ...