SpringBoot配置双数据源
SpringBoot配置双数据源
一、搭建springboot项目
二、添加依赖
<dependencies>
<!--web服务-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--测试-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--mybatis驱动-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!--druid连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.24</version>
</dependency>
<!--lombok插件-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!--数据实体类转化-->
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-jdk8</artifactId>
<version>1.2.0.Final</version>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>1.2.0.Final</version>
</dependency>
<!--aop依赖,事务所需要-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
</dependencies>
三、配置数据源
spring:
datasource:
master:
driver-class-name: com.mysql.jdbc.Driver
username: root
password: root
url: jdbc:mysql://localhost:3306/sys_user?serverTimezone=UTC&autoReconnect=true&useUnicode=true&characterEncoding=utf8&useSSL=false&allowMultiQueries=true
type: com.alibaba.druid.pool.DruidDataSource
second:
driver-class-name: com.mysql.jdbc.Driver
username: root
password: root
url: jdbc:mysql://localhost:3306/t_sys_user?serverTimezone=UTC&autoReconnect=true&useUnicode=true&characterEncoding=utf8&useSSL=false&allowMultiQueries=true
type: com.alibaba.druid.pool.DruidDataSource
#mybatis:
#config‐location: classpath:mybatis/mybatis‐config.xml #指定全局配置文件的位置
#mapper‐locations: classpath:mapper/*.xml
logging:
path: ./data_migration
level:
root: INFO
com.cxqy.data: DEBUG
四、编写数据源配置类
1、主数据源配置类 MasterDataSourceConfig
Configuration
@MapperScan(basePackages = MasterDataSourceConfig.PACKAGE, sqlSessionFactoryRef = "masterSqlSessionFactory")
public class MasterDataSourceConfig {
// 精确到 master 目录,以便跟其他数据源隔离
static final String PACKAGE = "com.cxqy.data.dao.master";
static final String MAPPER_LOCATION = "classpath:mapper/master/*.xml";
@Value("${spring.datasource.master.url}")
private String url;
@Value("${spring.datasource.master.username}")
private String user;
@Value("${spring.datasource.master.password}")
private String password;
@Value("${spring.datasource.master.driver-class-name}")
private String driverClass;
@Bean(name = "masterDataSource")
@Primary
public DataSource masterDataSource() {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName(driverClass);
dataSource.setUrl(url);
dataSource.setUsername(user);
dataSource.setPassword(password);
return dataSource;
}
@Bean(name = "masterTransactionManager")
@Primary
public DataSourceTransactionManager masterTransactionManager() {
return new DataSourceTransactionManager(masterDataSource());
}
@Bean(name = "masterSqlSessionFactory")
@Primary
public SqlSessionFactory masterSqlSessionFactory(@Qualifier("masterDataSource") DataSource masterDataSource)
throws Exception {
final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(masterDataSource);
sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
.getResources(MasterDataSourceConfig.MAPPER_LOCATION));
return sessionFactory.getObject();
}
}
2、副数据源配置类 SecondDataSourceConfig
@Configuration
@MapperScan(basePackages = SecondDataSourceConfig.PACKAGE, sqlSessionFactoryRef = "secondSqlSessionFactory")
public class SecondDataSourceConfig {
// 精确到 cluster 目录,以便跟其他数据源隔离
static final String PACKAGE = "com.cxqy.data.dao.second";
static final String MAPPER_LOCATION = "classpath:mapper/second/*.xml";
@Value("${spring.datasource.second.url}")
private String url;
@Value("${spring.datasource.second.username}")
private String user;
@Value("${spring.datasource.second.password}")
private String password;
@Value("${spring.datasource.second.driver-class-name}")
private String driverClass;
@Bean(name = "secondDataSource")
public DataSource clusterDataSource() {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName(driverClass);
dataSource.setUrl(url);
dataSource.setUsername(user);
dataSource.setPassword(password);
return dataSource;
}
@Bean(name = "secondTransactionManager")
public DataSourceTransactionManager clusterTransactionManager() {
return new DataSourceTransactionManager(clusterDataSource());
}
@Bean(name = "secondSqlSessionFactory")
public SqlSessionFactory clusterSqlSessionFactory(@Qualifier("secondDataSource") DataSource clusterDataSource)
throws Exception {
final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(clusterDataSource);
sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
.getResources(SecondDataSourceConfig.MAPPER_LOCATION));
return sessionFactory.getObject();
}
}
此时可以连接两个数据源进行业务编写。
注意避坑
在双数据源的情况下,事务可能会失效,这时候需要指定那一个数据库的操作需要进行事务,指定数据库事务名在配置类中。
1、在启动类BootdoApplication上添加@EnableTransactionManagement 注解
2、在service层添加@Transactional注解
@Transactional(readOnly = true,rollbackFor = Exception.class,transactionManager = "secondTransactionManager",isolation = Isolation.READ_UNCOMMITTED,propagation = Propagation.REQUIRED)
3、查看置顶数据库事务名,在数据源配置类中查看
SpringBoot配置双数据源的更多相关文章
- springboot配置双数据源 MySQL和SqlServer
1. pom文件的驱动jar包加上去, compile 'com.microsoft.sqlserver:mssql-jdbc:6.2.2.jre8' 2. application.yml sprin ...
- spring项目配置双数据源读写分离
我们最早做新项目的时候一直想做数据库的读写分离与主从同步,由于一些原因一直没有去做这个事情,这次我们需要配置双数据源的起因是因为我们做了一个新项目用了另一个数据库,需要把这个数据库的数据显示到原来的后 ...
- springboot配置Druid数据源
springboot配置druid数据源 Author:SimpleWu springboot整合篇 前言 对于数据访问层,无论是Sql还是NoSql,SpringBoot默认采用整合SpringDa ...
- SpringBoot配置多数据源时遇到的问题
SpringBoot配置多数据源 参考代码:Spring Boot 1.5.8.RELEASE同时配置Oracle和MySQL 原作者用的是1.5.8版本的SpringBoot,在升级到2.0.*之后 ...
- springboot 配置多数据源
1.首先在创建应用对象时引入autoConfig package com; import org.springframework.boot.SpringApplication; import org. ...
- spring+mybatis 配置双数据源
配置好后,发现网上已经做好的了, 不过,跟我的稍有不同, 我这里再拿出来现个丑: properties 文件自不必说,关键是这里的xml: <?xml version="1.0&quo ...
- springboot配置双视图解析器
因项目要求,需要同时支持html和jsp页面,所以在springboot的基础上配置双视图解析器. 重点在于,抛开原来的resources目录结构层,这层只放application.propertie ...
- springboot 配置多数据源 good
1.首先在创建应用对象时引入autoConfig package com; import org.springframework.boot.SpringApplication; import org. ...
- spring boot 配置双数据源mysql、sqlServer
背景:原来一直都是使用mysql数据库,在application.properties 中配置数据库信息 spring.datasource.url=jdbc:mysql://xxxx/test sp ...
- springboot配置多数据源mybatis配置失效问题
mybatis配置 #开启驼峰映射 mybatis.configuration.map-underscore-to-camel-case=true #开启打印sql mybatis.configura ...
随机推荐
- redis 集群配置(从0到1)
1.关闭配置文件 appendonly yes改为no 2.到redis目录下拷贝redis.conf文件 cp ./redis.conf ./7001/ cp ./redis.conf ./7002 ...
- ABAP 写入批次特征值以及更新批次特征值
需求 SAP启用了批次,需要在特征值中写入物料类型,区分该物料批次是用于研发的亦或是量产的,关于研发和量产标识我是坐在采购订单行项目增强中了,这里就不多赘述了,参考https://www.cnblog ...
- iOS 常用第三方库及原理
AFNetWorking SDWebImage MJRefresh Masonry YYModel IQKeyboardManger
- day01-java流程
Scanner对象 基本语法: Scanner s = new Scanner(System.in); next()方法 nextLine()方法 顺序结构 选择结构 if单选结构 语法: if(布尔 ...
- vue 基础 v-text v-html v-model v-cloak v-bind
v-text 纯文本绑定 v-html 会解析html标签 <p v-html="rawHtml"></p> var a=new Vue({ el:&q ...
- 微信带参数的小程序码生成并上传到七牛云(java)
在大家看正式内容之前请耐心的听我把这段话说完:我冒昧的猜一下,你为了解决问题估计已经看了很多文章了,如果这边文章能给你带来帮助,不胜荣幸,如果有错误也请批评指正,共同进步,我之前在完成这个功能之前,从 ...
- Warning: PHP Startup: Unable to load dynamic library
使用 phpstudy时,一直提示找不到指定的模块,但是在我对应的文件里面是有该模块的 且 php.ini中 对应的语句注释也已打开 我遇见该问题解决方法是:php版本与这个拓展的版本不对应 ,把版 ...
- docker自动化启动停止脚本
docker一键启动命令 sh auto.sh [start|restart|stop] [keywords...] keywords可选(包含编号,镜像名,容器名称,端口) 其中defaultLis ...
- JAVA诞生历史【转载】
一.计算机语言的发展史 1.第一代语言(只有机器能读懂,人根本读不懂) 纯机器语言 2.第二代语言(机器能读懂,人可以读懂,但是很难懂) 汇编语言(符号语言) 3.第三代语言(机器能读懂,也非常便于人 ...
- MySQL数据库SQL语法常规操作
必备sql和表关系及授权 graph LR 执行1[必备sql和授权] 执行2[SQL强化和实践] 执行3[索引和函数以及存储过程] 执行4[Python操作mysql和应用] 执行5[常见SQL语句 ...