1. <link rel="stylesheet" href="https://csdnimg.cn/release/phoenix/template/css/ck_htmledit_views-cd6c485e8b.css">
  2. <div id="content_views" class="markdown_views">
  3. <!-- flowchart 箭头图标 勿删 -->
  4. <svg xmlns="http://www.w3.org/2000/svg" style="display: none;">
  5. <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>
  6. </svg>
  7. <p>  在开发的过程中我们可能都会遇到对接公司其他系统等需求,对于外部的系统可以采用接口对接的方式,对于一个公司开发的两个系统,并且知道相关数据库结构的情况下,就可以考虑使用多数据源来解决这个问题。SpringBoot为我们提供了相对简单的实现。</p>

一、建立如下结构的maven项目

二、添加相关数据库配置信息

  1. server:
  2. port: 8080
  3. spring:
  4. datasource:
  5. master:
  6. driver-class-name: com.mysql.jdbc.Driver
  7. url: jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false
  8. username: root
  9. password: 123456
  10. slaver:
  11. driver-class-name: com.mysql.jdbc.Driver
  12. url: jdbc:mysql://127.0.0.1:3306/dev?useUnicode=true&characterEncoding=utf-8&useSSL=false
  13. username: root
  14. password: 123456
  15.  
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

三、主库和从库的相关配置

1、主库数据源配置

  1. @Configuration
  2. @MapperScan(basePackages = "com.somta.springboot.dao.master", sqlSessionTemplateRef = "masterSqlSessionTemplate")
  3. public class MasterDataSourceConfiguration {
  4. @Value("${spring.datasource.master.driver-class-name}")
  5. private String driverClassName;
  6. @Value("${spring.datasource.master.url}")
  7. private String url;
  8. @Value("${spring.datasource.master.username}")
  9. private String username;
  10. @Value("${spring.datasource.master.password}")
  11. private String password;
  12. @Bean(name = "masterDataSource")
  13. @Primary
  14. public DataSource dataSource() {
  15. DruidDataSource dataSource = new DruidDataSource();
  16. dataSource.setDriverClassName(this.driverClassName);
  17. dataSource.setUrl(this.url);
  18. dataSource.setUsername(this.username);
  19. dataSource.setPassword(this.password);
  20. return dataSource;
  21. }
  22. @Bean(name = "masterSqlSessionFactory")
  23. @Primary
  24. public SqlSessionFactory sqlSessionFactory(@Qualifier("masterDataSource") DataSource dataSource) throws Exception {
  25. SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
  26. bean.setDataSource(dataSource);
  27. bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mybatis/master/**/Mysql_*Mapper.xml"));
  28. return bean.getObject();
  29. }
  30. @Bean(name = "masterTransactionManager")
  31. @Primary
  32. public DataSourceTransactionManager transactionManager(@Qualifier("masterDataSource") DataSource dataSource) {
  33. return new DataSourceTransactionManager(dataSource);
  34. }
  35. @Bean(name = "masterSqlSessionTemplate")
  36. @Primary
  37. public SqlSessionTemplate sqlSessionTemplate(@Qualifier("masterSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
  38. return new SqlSessionTemplate(sqlSessionFactory);
  39. }
  40. }
  41.  
    • 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、从库的数据源配置信息

  1. @Configuration
  2. @MapperScan(basePackages = "com.somta.springboot.dao.slaver", sqlSessionTemplateRef = "slaverSqlSessionTemplate")
  3. public class SlaverDataSourceConfiguration {
  4. @Value("${spring.datasource.slaver.driver-class-name}")
  5. private String driverClassName;
  6. @Value("${spring.datasource.slaver.url}")
  7. private String url;
  8. @Value("${spring.datasource.slaver.username}")
  9. private String username;
  10. @Value("${spring.datasource.slaver.password}")
  11. private String password;
  12. @Bean(name = "slaverDataSource")
  13. public DataSource dataSource() {
  14. DruidDataSource dataSource = new DruidDataSource();
  15. dataSource.setDriverClassName(this.driverClassName);
  16. dataSource.setUrl(this.url);
  17. dataSource.setUsername(this.username);
  18. dataSource.setPassword(this.password);
  19. return dataSource;
  20. }
  21. @Bean(name = "slaverSqlSessionFactory")
  22. public SqlSessionFactory sqlSessionFactory(@Qualifier("slaverDataSource") DataSource dataSource) throws Exception {
  23. SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
  24. bean.setDataSource(dataSource);
  25. bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mybatis/slaver/**/Mysql_*Mapper.xml"));
  26. return bean.getObject();
  27. }
  28. @Bean(name = "slaverTransactionManager")
  29. public DataSourceTransactionManager transactionManager(@Qualifier("slaverDataSource") DataSource dataSource) {
  30. return new DataSourceTransactionManager(dataSource);
  31. }
  32. @Bean(name = "slaverSqlSessionTemplate")
  33. public SqlSessionTemplate sqlSessionTemplate(@Qualifier("slaverSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
  34. return new SqlSessionTemplate(sqlSessionFactory);
  35. }
  36. }
  37.  
    • 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

  1. public interface UserMasterDao {
  2. int addUser(User user);
  3. int deleteUserById(Long id);
  4. int updateUserById(User user);
  5. User queryUserById(Long id);
  6. List<User> queryUserList();
  7. }
  8.  
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper
  3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  5. <mapper namespace="com.somta.springboot.dao.master.UserMasterDao" >
  6. <!-- Result Map-->
  7. <resultMap id="BaseResultMap" type="com.somta.springboot.pojo.User" >
  8. <result column="id" property="id"/>
  9. <result column="name" property="name"/>
  10. <result column="age" property="age"/>
  11. </resultMap>
  12. <!-- th_role_user table all fields -->
  13. <sql id="Base_Column_List" >
  14. id, name, age
  15. </sql>
  16. <insert id="addUser" parameterType="com.somta.springboot.pojo.User" >
  17. insert into t_user (id, name, age)
  18. values (#{id},#{name},#{age});
  19. </insert>
  20. <delete id="deleteUserById" parameterType="java.lang.Long">
  21. delete from t_user where id=#{id}
  22. </delete>
  23. <update id="updateUserById" parameterType="com.somta.springboot.pojo.User" >
  24. update t_user set
  25. <trim suffixOverrides="," >
  26. <if test="id != null and id != ''">
  27. id=#{id},
  28. </if>
  29. <if test="name != null and name != ''">
  30. name=#{name},
  31. </if>
  32. <if test="age != null and age != ''">
  33. age=#{age},
  34. </if>
  35. </trim> where id=#{id}
  36. </update>
  37. <select id="queryUserById" resultMap="BaseResultMap" parameterType="java.lang.Long">
  38. select <include refid="Base_Column_List" />
  39. from t_user where id = #{id}
  40. </select>
  41. <select id="queryUserList" resultMap="BaseResultMap">
  42. select <include refid="Base_Column_List" />
  43. from t_user
  44. </select>
  45. </mapper>
  46.  
    • 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

五、编写测试类进行测试

  1. @RunWith(SpringJUnit4ClassRunner.class)
  2. @SpringBootTest(classes = Application.class)
  3. public class MultiDatasourceTest {
  4. @Autowired
  5. private UserMasterDao masterUserDao;
  6. @Autowired
  7. private UserSlaverDao slaverUserDao;
  8. /**
  9. * 查询用户
  10. * @throws Exception
  11. */
  12. @Test
  13. public void testQueryUser() throws Exception {
  14. User masterUser = masterUserDao.queryUserById(1L);
  15. System.out.println("masterUser==>"+masterUser.getName());
  16. User slaverUser = slaverUserDao.queryUserById(1L);
  17. System.out.println("slaverUser==>"+slaverUser.getName());
  18. }
  19. }
  20.  
    • 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

  1. </div>
  2. <link href="https://csdnimg.cn/release/phoenix/mdeditor/markdown_views-e44c3c0e64.css" rel="stylesheet">

原文地址:https://blog.csdn.net/husong_/article/details/80103497

SpringBoot2.0--- 多数据源配置的更多相关文章

  1. springboot2.0双数据源配置

    题记:由于项目中不只是用一个数据库,所以记下以免忘记. 1.首先展示目录结构 2.pom配置文件 <?xml version="1.0" encoding="UTF ...

  2. SpringBoot(十一):springboot2.0.2下配置mybatis generator环境,并自定义字段/getter/settetr注释

    Mybatis Generator是供开发者在mybatis开发时,快速构建mapper xml,mapper类,model类的一个插件工具.它相对来说对开发者是有很大的帮助的,但是它也有不足之处,比 ...

  3. springboot学习入门简易版八---springboot2.0多环境配置、整合mybatis mysql8+(19-20)

    2.11 SpringBoot多环境配置(19)  application.properties中配置 Spring.profiles.active=prd 配置环境: Application-dev ...

  4. SpringBoot2.0的CacheManager配置

    http://rickgong.iteye.com/blog/2414263 @Configurationpublic class RedisConfig extends CachingConfigu ...

  5. IntelliJ IDEA 2017版 spring-boot2.0.2 自动配置Condition

    描述: 编译器修改参数      -Dfile.encoding=GBK     -Dstr.encoding=GBK Condition位置: 某一个类或注解存在的时候,装配,否则不装配 相关代码: ...

  6. springboot2.0动态多数据源切换

    摘要:springboot1.x到springboot2.0配置变化有一点变化,网上关于springboot2.0配置多数据源的资料也比较少,为了让大家配置多数据源从springboot1.x升级到s ...

  7. SpringBoot2.0 基础案例(14):基于Yml配置方式,实现文件上传逻辑

    本文源码 GitHub地址:知了一笑 https://github.com/cicadasmile/spring-boot-base 一.文件上传 文件上传是项目开发中一个很常用的功能,常见的如头像上 ...

  8. 升级项目版本:SpringBoot1.5.x到SpringBoot2.0.x

    1.升级版本的选择 首先去spring的官网看一下最新的版本与版本之间的依赖

  9. SpringBoot2.0 基础案例(06):引入JdbcTemplate,和多数据源配置

    一.JdbcTemplate对象 1.JdbcTemplate简介 在Spring Boot2.0框架下配置数据源和通过JdbcTemplate访问数据库的案例. SpringBoot对数据库的操作在 ...

  10. SpringBoot2.0之八 多数据源配置

     在开发的过程中我们可能都会遇到对接公司其他系统等需求,对于外部的系统可以采用接口对接的方式,对于一个公司开发的两个系统,并且知道相关数据库结构的情况下,就可以考虑使用多数据源来解决这个问题.Spri ...

随机推荐

  1. DirectX11笔记(十)--Direct3D渲染6--PIXEL SHADER

    原文:DirectX11笔记(十)--Direct3D渲染6--PIXEL SHADER 版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/u01033 ...

  2. Leetcode874.Walking Robot Simulation模拟行走的机器人

    机器人在一个无限大小的网格上行走,从点 (0, 0) 处开始出发,面向北方.该机器人可以接收以下三种类型的命令: -2:向左转 90 度 -1:向右转 90 度 1 <= x <= 9:向 ...

  3. JQuery-- 实例:小米左右切图,淡入淡出,自动,小圆点触发轮播图

    示意图: demo <!DOCTYPE html> <html lang="en"> <head> <meta charset=" ...

  4. 编程语言分类及python所属类型

    编程语言分类及python所属类型 编程语言主要从以下几个角度为进行分类:编译型和解释型.静态语言和动态语言.强类型定义语言和弱类型定义语言. 编译和解释的区别是什么? 编译器是把源程序的每一条语句都 ...

  5. pl/sql基础知识—定义并使用变量

    n  介绍 在编写pl/sql程序是,可以定义变量和常量:在pl/sql程序中包括有: ①标量类型(scalar) ②复合类型(composite) ③参照类型(reference) ④lob(lar ...

  6. TCPThree_C杯 Day1

    题解 或 正规题解 已经很详细,不再赘述. 跟着wjx打代码,不怕卡题. 忘开long long智障错误第四次左偏树

  7. Xcode10 import导入文件的坑

    更新了10.0的Xcode,踩了两个坑,记录一下. #import "" 双引号内输入任何字符 都会导致Xcode崩溃 解决方案: target - buildSettings - ...

  8. [转]The Curse of Dimensionality(维数灾难)

    原文章地址:维度灾难 - 柳枫的文章 - 知乎 https://zhuanlan.zhihu.com/p/27488363 对于大多数数据,在一维空间或者说是低维空间都是很难完全分割的,但是在高纬空间 ...

  9. docker查看运行容器详细信息

    使用docker ps命令可以查看所有正在运行中的容器列表, 使用docker inspect命令我们可以查看更详细的关于某一个容器的信息. $ docker inspect 容器id/image

  10. HZOJ 毛一琛

    直接暴搜是$3^n$的,无法接受. 正解是$meet \ in \ the \ middle$,暴搜前n/2个数,每个数的状态有三种:都不选,选为A集合,选为B集合.那么我们可以维护两个集合的差. 设 ...