SpringBoot2.0之八 多数据源配置
在开发的过程中我们可能都会遇到对接公司其他系统等需求,对于外部的系统可以采用接口对接的方式,对于一个公司开发的两个系统,并且知道相关数据库结构的情况下,就可以考虑使用多数据源来解决这个问题。SpringBoot为我们提供了相对简单的实现。
一、建立如下结构的maven项目
二、添加相关数据库配置信息
server:
port: 8080
spring:
datasource:
master:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false
username: root
password: 123456
slaver:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/dev?useUnicode=true&characterEncoding=utf-8&useSSL=false
username: root
password: 123456
三、主库和从库的相关配置
1、主库数据源配置
@Configuration
@MapperScan(basePackages = "com.somta.springboot.dao.master", sqlSessionTemplateRef = "masterSqlSessionTemplate")
public class MasterDataSourceConfiguration {
@Value("${spring.datasource.master.driver-class-name}")
private String driverClassName;
@Value("${spring.datasource.master.url}")
private String url;
@Value("${spring.datasource.master.username}")
private String username;
@Value("${spring.datasource.master.password}")
private String password;
@Bean(name = "masterDataSource")
@Primary
public DataSource dataSource() {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName(this.driverClassName);
dataSource.setUrl(this.url);
dataSource.setUsername(this.username);
dataSource.setPassword(this.password);
return dataSource;
}
@Bean(name = "masterSqlSessionFactory")
@Primary
public SqlSessionFactory sqlSessionFactory(@Qualifier("masterDataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mybatis/master/**/Mysql_*Mapper.xml"));
return bean.getObject();
}
@Bean(name = "masterTransactionManager")
@Primary
public DataSourceTransactionManager transactionManager(@Qualifier("masterDataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
@Bean(name = "masterSqlSessionTemplate")
@Primary
public SqlSessionTemplate sqlSessionTemplate(@Qualifier("masterSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
return new SqlSessionTemplate(sqlSessionFactory);
}
}
2、从库的数据源配置信息
@Configuration
@MapperScan(basePackages = "com.somta.springboot.dao.slaver", sqlSessionTemplateRef = "slaverSqlSessionTemplate")
public class SlaverDataSourceConfiguration {
@Value("${spring.datasource.slaver.driver-class-name}")
private String driverClassName;
@Value("${spring.datasource.slaver.url}")
private String url;
@Value("${spring.datasource.slaver.username}")
private String username;
@Value("${spring.datasource.slaver.password}")
private String password;
@Bean(name = "slaverDataSource")
public DataSource dataSource() {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName(this.driverClassName);
dataSource.setUrl(this.url);
dataSource.setUsername(this.username);
dataSource.setPassword(this.password);
return dataSource;
}
@Bean(name = "slaverSqlSessionFactory")
public SqlSessionFactory sqlSessionFactory(@Qualifier("slaverDataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mybatis/slaver/**/Mysql_*Mapper.xml"));
return bean.getObject();
}
@Bean(name = "slaverTransactionManager")
public DataSourceTransactionManager transactionManager(@Qualifier("slaverDataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
@Bean(name = "slaverSqlSessionTemplate")
public SqlSessionTemplate sqlSessionTemplate(@Qualifier("slaverSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
return new SqlSessionTemplate(sqlSessionFactory);
}
}
注意在配置数据源的信息时,一定要通过@Primary配置一个主库,对于数据库配置部分与普通的数据源配置没有差异,新建一个DataSource,在创建一个SqlSessionTemplate,最后创建一个SqlSessionTemplate,分别以此注入即可,@MapperScan注解的扫描路径要分别对于相应的dao层
四、编写dao层和xml
public interface UserMasterDao {
int addUser(User user);
int deleteUserById(Long id);
int updateUserById(User user);
User queryUserById(Long id);
List<User> queryUserList();
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.somta.springboot.dao.master.UserMasterDao" >
<!-- Result Map-->
<resultMap id="BaseResultMap" type="com.somta.springboot.pojo.User" >
<result column="id" property="id"/>
<result column="name" property="name"/>
<result column="age" property="age"/>
</resultMap>
<!-- th_role_user table all fields -->
<sql id="Base_Column_List" >
id, name, age
</sql>
<insert id="addUser" parameterType="com.somta.springboot.pojo.User" >
insert into t_user (id, name, age)
values (#{id},#{name},#{age});
</insert>
<delete id="deleteUserById" parameterType="java.lang.Long">
delete from t_user where id=#{id}
</delete>
<update id="updateUserById" parameterType="com.somta.springboot.pojo.User" >
update t_user set
<trim suffixOverrides="," >
<if test="id != null and id != ''">
id=#{id},
</if>
<if test="name != null and name != ''">
name=#{name},
</if>
<if test="age != null and age != ''">
age=#{age},
</if>
</trim> where id=#{id}
</update>
<select id="queryUserById" resultMap="BaseResultMap" parameterType="java.lang.Long">
select <include refid="Base_Column_List" />
from t_user where id = #{id}
</select>
<select id="queryUserList" resultMap="BaseResultMap">
select <include refid="Base_Column_List" />
from t_user
</select>
</mapper>
五、编写测试类进行测试
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Application.class)
public class MultiDatasourceTest {
@Autowired
private UserMasterDao masterUserDao;
@Autowired
private UserSlaverDao slaverUserDao;
/**
* 查询用户
* @throws Exception
*/
@Test
public void testQueryUser() throws Exception {
User masterUser = masterUserDao.queryUserById(1L);
System.out.println("masterUser==>"+masterUser.getName());
User slaverUser = slaverUserDao.queryUserById(1L);
System.out.println("slaverUser==>"+slaverUser.getName());
}
}
当在控制台看到如下所示输出就代表我们的配置已经成功了
Git代码地址:https://gitee.com/Somta/SpringBoot/tree/master/SpringBoot-multiDatasource
原文地址:http://somta.com.cn/#/blog/view/05ef234aa6744aa4bc039869e2cfaffe
---------------------
作者:明天的地平线
来源:CSDN
原文:https://blog.csdn.net/husong_/article/details/80103497
版权声明:本文为博主原创文章,转载请附上博文链接!
SpringBoot2.0之八 多数据源配置的更多相关文章
- springboot2.0+mybatis多数据源集成
最近在学springboot,把学的记录下来.主要有springboot2.0+mybatis多数据源集成,logback日志集成,springboot单元测试. 一.代码结构如下 二.pom.xml ...
- springboot2.0动态多数据源切换
摘要:springboot1.x到springboot2.0配置变化有一点变化,网上关于springboot2.0配置多数据源的资料也比较少,为了让大家配置多数据源从springboot1.x升级到s ...
- springboot学习入门简易版九---springboot2.0整合多数据源mybatis mysql8+(22)
一个项目中配置多个数据源(链接不同库jdbc),无限大,具体多少根据内存大小 项目中多数据源如何划分:分包名(业务)或注解方式.分包名方式类似多个不同的jar,同业务需求放一个包中. 分包方式配置多数 ...
- springboot2.0和Druid整合配置数据源
1. idea使用spring 初始化工具初始化springboot项目(要选中web) 下一步,下一步 2. 在pom.xml中,引入Druid连接池依赖: <dependency> & ...
- SpringBoot2.0之六 多环境配置
开发过程中面对不同的环境,例如数据库.redis服务器等的不同,可能会面临一直需要修改配置的麻烦中,在以前的项目中,曾通过Tomcat的配置来实现,有的项目甚至需要手动修改相关配置,这种方式费时费力, ...
- springboot2.0 redis EnableCaching的配置和使用
一.前言 关于EnableCaching最简单使用,个人感觉只需提供一个CacheManager的一个实例就好了.springboot为我们提供了cache相关的自动配置.引入cache模块,如下. ...
- IntelliJ IDEA 2017版 spring-boot2.0.4的yml配置使用
一.必须配置字端两个 server: port: 8080 servlet: context-path: /demo 二.两种mvc转换springboot,一种是注解,一种就是.yml或proper ...
- IntellJ IDEA2017 springboot2.0.2中读取配置
IDEA 路径 src\main\resources\application.properties 配置文件名称为 application.properties 默认的位置在classpath根目录下 ...
- springboot2.0最精简的配置yml
https://blog.csdn.net/yu_hongrun/article/details/81708762
随机推荐
- maven 编译出错Fatal error compiling: 无效的目标发行版: 1.8 -> [Help 1] 解决办法
这几天在为公司项目搭建一个后台框架,使用的是eclipse-Mars自带的maven插件,在maven进行编译的时候,出现Fatal error compiling: 无效的目标发行版: 1.8 -& ...
- Asp.Net Core 2.0 项目实战(6)Redis配置、封装帮助类RedisHelper及使用实例
本文目录 1. 摘要 2. Redis配置 3. RedisHelper 4.使用实例 5. 总结 1. 摘要 由于內存存取速度远高于磁盘读取的特性,为了程序效率提高性能,通常会把常用的不常变动的数 ...
- 数据结构 之 并查集(Disjoint Set)
一.并查集的概念: 首先,为了引出并查集,先介绍几个概念: 1.等价关系(Equivalent Relation) 自反性.对称性.传递性. 如果a和b存在等价关系,记 ...
- 【手记】解决启动SQL Server Management Studio 17时报Cannot find one of more components...的问题
刚装好SSMS 17.1准备体验,弹出: 一番搜索,普遍办法都是安装VS2015独立shell.删除某个注册表项什么的,没用,首先这个shell我是装了的,然后也没有那个注册表项.我自己尝试过重装sh ...
- js算法初窥03(简单搜索及去重算法)
前面我们了解了一些常用的排序算法,那么这篇文章我们来看看搜索算法的一些简单实现,我们先来介绍一个我们在实际工作中一定用到过的搜索算法--顺序搜索. 1.顺序搜索 其实顺序搜索十分简单,我们还是以第一篇 ...
- jmeter使用csv进行参数化(一)
先录制一个脚本,具体录制可以参考笔者的随笔:http://www.cnblogs.com/wuyazi/p/8889770.html 1.准备参数化文本内容:mac没有自带的txt文本编辑器,笔者是在 ...
- ajax技术基础详解
一.概述 1.什么是ajax 可以与服务器进行[异步]交互的技术,浏览器无需刷新 2.什么时候出现ajax? -- XMLHttp 微软 1999年微软公司发布IE5版本,内嵌了ajax技术 什么时候 ...
- segment.go
package sego // 文本中的一个分词 type Segment struct { // 分词在文本中的起始字节位置 start int // 分词在文本中的结束字节 ...
- [codeforces 901E] Cyclic Cipher 循环卷积-Bluestein's Algorithm
题目大意: 传送门 给两个数列${B_i}.{C_i}$,长度均为$n$,且${B_i}$循环移位线性无关,即不存在一组系数${X_i}$使得对于所有的$k$均有$\sum_{i=0}^{n-1} X ...
- bzoj3289 Mato的文件管理 莫队+树状数组
求逆序对个数,莫队套树状数组 #include<cstdio> #include<iostream> #include<cstring> #include<c ...