SpringBoot2.0--- 多数据源配置
<link rel="stylesheet" href="https://csdnimg.cn/release/phoenix/template/css/ck_htmledit_views-cd6c485e8b.css">
<div id="content_views" class="markdown_views">
<!-- flowchart 箭头图标 勿删 -->
<svg xmlns="http://www.w3.org/2000/svg" style="display: none;">
<path stroke-linecap="round" d="M5,0 0,2.5 5,5z" id="raphael-marker-block" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);"></path>
</svg>
<p> 在开发的过程中我们可能都会遇到对接公司其他系统等需求,对于外部的系统可以采用接口对接的方式,对于一个公司开发的两个系统,并且知道相关数据库结构的情况下,就可以考虑使用多数据源来解决这个问题。SpringBoot为我们提供了相对简单的实现。</p>
一、建立如下结构的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
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
三、主库和从库的相关配置
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);
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
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);
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
注意在配置数据源的信息时,一定要通过@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();
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
<?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>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
五、编写测试类进行测试
@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());
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
当在控制台看到如下所示输出就代表我们的配置已经成功了
Git代码地址:https://gitee.com/Somta/SpringBoot/tree/master/SpringBoot-multiDatasource
原文地址:http://somta.com.cn/#/blog/view/05ef234aa6744aa4bc039869e2cfaffe
</div>
<link href="https://csdnimg.cn/release/phoenix/mdeditor/markdown_views-e44c3c0e64.css" rel="stylesheet">
SpringBoot2.0--- 多数据源配置的更多相关文章
- springboot2.0双数据源配置
题记:由于项目中不只是用一个数据库,所以记下以免忘记. 1.首先展示目录结构 2.pom配置文件 <?xml version="1.0" encoding="UTF ...
- SpringBoot(十一):springboot2.0.2下配置mybatis generator环境,并自定义字段/getter/settetr注释
Mybatis Generator是供开发者在mybatis开发时,快速构建mapper xml,mapper类,model类的一个插件工具.它相对来说对开发者是有很大的帮助的,但是它也有不足之处,比 ...
- springboot学习入门简易版八---springboot2.0多环境配置、整合mybatis mysql8+(19-20)
2.11 SpringBoot多环境配置(19) application.properties中配置 Spring.profiles.active=prd 配置环境: Application-dev ...
- SpringBoot2.0的CacheManager配置
http://rickgong.iteye.com/blog/2414263 @Configurationpublic class RedisConfig extends CachingConfigu ...
- IntelliJ IDEA 2017版 spring-boot2.0.2 自动配置Condition
描述: 编译器修改参数 -Dfile.encoding=GBK -Dstr.encoding=GBK Condition位置: 某一个类或注解存在的时候,装配,否则不装配 相关代码: ...
- springboot2.0动态多数据源切换
摘要:springboot1.x到springboot2.0配置变化有一点变化,网上关于springboot2.0配置多数据源的资料也比较少,为了让大家配置多数据源从springboot1.x升级到s ...
- SpringBoot2.0 基础案例(14):基于Yml配置方式,实现文件上传逻辑
本文源码 GitHub地址:知了一笑 https://github.com/cicadasmile/spring-boot-base 一.文件上传 文件上传是项目开发中一个很常用的功能,常见的如头像上 ...
- 升级项目版本:SpringBoot1.5.x到SpringBoot2.0.x
1.升级版本的选择 首先去spring的官网看一下最新的版本与版本之间的依赖
- SpringBoot2.0 基础案例(06):引入JdbcTemplate,和多数据源配置
一.JdbcTemplate对象 1.JdbcTemplate简介 在Spring Boot2.0框架下配置数据源和通过JdbcTemplate访问数据库的案例. SpringBoot对数据库的操作在 ...
- SpringBoot2.0之八 多数据源配置
在开发的过程中我们可能都会遇到对接公司其他系统等需求,对于外部的系统可以采用接口对接的方式,对于一个公司开发的两个系统,并且知道相关数据库结构的情况下,就可以考虑使用多数据源来解决这个问题.Spri ...
随机推荐
- OpenLayers在地图外放置控件
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head ...
- android studio离线打包mui应用
版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/foolish0421/article/details/54618754首先从官网http://www ...
- Kryo官方文档-中文翻译
Kryo作为一个优秀的Java序列化方案,在网上能找到不少测评,但未见系统的中文入门或说明文档.官方文档是最好的学习文档.虽然英文不差,但啃下来毕竟没母语来的舒服.这里抽出时间做些翻译,以方便大家查阅 ...
- 学习String类
1. 描述: String类是java中比较常用的类, 表示字符串类型 当拼接大量数据时, String类性能没有StringBuilder和StringBuffer性能高 2. 常用的String语 ...
- 时间模块(import time)
时间戳时间: float数据类型,给机器用的 print(time.time()) =>1533713657.5423343 结构化时间: 上下两种格式的中间状态 能够通过属性名来获取对象中的值 ...
- 【转】Jython安装(Win)
ython的安装比较简单,Jython的安装程序本身就是一个Java应用程序,因此,在安装之前,你必须具备Java运行的环境.下面以 Jython的Jython2.2.1为例,说明Jython的安装步 ...
- Auto reloading enabled
在eclipse中集成tomcat来开发时, 如果使用run as模式启动项目的话,tomcat配置Auto reloading enabled,我们修改java文件,项目会重新加载,修改的内容会生效 ...
- TensorFlow3学习笔记1
1.简单实例:向量相加 下面我们通过两个向量相加的简单例子来看一下Tensorflow的基本用法. [1. 1. 1. 1.] + [2. 2. 2. 2.] = [3. 3. 3. 3.] impo ...
- Java练习 SDUT-2445_小学数学
小学数学 Time Limit: 1000 ms Memory Limit: 65536 KiB Problem Description 今年中秋节,大宝哥带着一盒月饼去看望小学数学老师.碰巧数学老师 ...
- 【Leetcode链表】两两交换链表中的节点(24)
题目 给定一个链表,两两交换其中相邻的节点,并返回交换后的链表.你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换. 示例: 给定 1->2->3->4, 你应该返回 2- ...