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配置双数据源的更多相关文章

  1. springboot配置双数据源 MySQL和SqlServer

    1. pom文件的驱动jar包加上去, compile 'com.microsoft.sqlserver:mssql-jdbc:6.2.2.jre8' 2. application.yml sprin ...

  2. spring项目配置双数据源读写分离

    我们最早做新项目的时候一直想做数据库的读写分离与主从同步,由于一些原因一直没有去做这个事情,这次我们需要配置双数据源的起因是因为我们做了一个新项目用了另一个数据库,需要把这个数据库的数据显示到原来的后 ...

  3. springboot配置Druid数据源

    springboot配置druid数据源 Author:SimpleWu springboot整合篇 前言 对于数据访问层,无论是Sql还是NoSql,SpringBoot默认采用整合SpringDa ...

  4. SpringBoot配置多数据源时遇到的问题

    SpringBoot配置多数据源 参考代码:Spring Boot 1.5.8.RELEASE同时配置Oracle和MySQL 原作者用的是1.5.8版本的SpringBoot,在升级到2.0.*之后 ...

  5. springboot 配置多数据源

    1.首先在创建应用对象时引入autoConfig package com; import org.springframework.boot.SpringApplication; import org. ...

  6. spring+mybatis 配置双数据源

    配置好后,发现网上已经做好的了, 不过,跟我的稍有不同, 我这里再拿出来现个丑: properties 文件自不必说,关键是这里的xml: <?xml version="1.0&quo ...

  7. springboot配置双视图解析器

    因项目要求,需要同时支持html和jsp页面,所以在springboot的基础上配置双视图解析器. 重点在于,抛开原来的resources目录结构层,这层只放application.propertie ...

  8. springboot 配置多数据源 good

    1.首先在创建应用对象时引入autoConfig package com; import org.springframework.boot.SpringApplication; import org. ...

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

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

  10. springboot配置多数据源mybatis配置失效问题

    mybatis配置 #开启驼峰映射 mybatis.configuration.map-underscore-to-camel-case=true #开启打印sql mybatis.configura ...

随机推荐

  1. react快速创建组件

    安装ES7插件  组件页面输入rcc

  2. mybatis处理多对一的映射关系

    创建数据库t_emp和t_dept 创建对应实体类 package org.example.entity; public class Emp { private Integer empId; priv ...

  3. react 05 router

    安装 npm i react-router-dom -- save<Router basename="/admin"> <Route path="/&q ...

  4. 05 RDD练习:词频统计,学习课程分数

    .词频统计: 1.读文本文件生成RDD lines 2.将一行一行的文本分割成单词 words flatmap() 3.全部转换为小写 lower() 4.去掉长度小于3的单词 filter() 5. ...

  5. Python语言基础实验(第四周)

    Python语言基础实验(第四周) 一.实验目的 1.了解并掌握python中序列及序列的常用操作. 2.根据实际需要运用合适的序列类型来完成实验. 二.实验环境 软件版本:Python 3.10 6 ...

  6. golang 数组(array)

    1. 概念 golang中的数组是具有固定长度及相同数据类型的序列集合 2. 初始化数组 var 数组名 [数组大小]数据类型 package main import "fmt" ...

  7. [jQuery]判断页面是否滚动到底部

    方法1:判断可见高度+滚动高度是否等于内容高度 但经过测试UC.QQ.华为浏览器,这个方法不生效.(打印查因:可能由于屏幕缩放,可见高度和滚动高度会偏小. $(this).scroll(functio ...

  8. WampServer3.0服务器端开启ssl认证后重启Apache失败,解决办法

    最近项目中需要访问网站的 https 地址,于是进行部署,什么事情都是想起来简单,做起来难,想着一天就能搞定的事儿,结果前后折腾了三天. 现在把部署的经历记录下来,希望对朋友们有所帮助. 1.在西部数 ...

  9. docker容器部署flask单页面应用

    本地安装docker,拉取centos镜像. docker pull centos:7 本地文件结构: /usr/local/var/tmp/docker_demo .app ---requireme ...

  10. java8线程池创建并使用

    1.创建@Configurationpublic class ThreadPoolConfig { /** * 创建线程池 */ @Bean(name = "threadPool" ...