引言

从8月份到现在,团队一直有一项资源整合迁移的任务。简单来说,原来的产品设计规划不合理,各业务组各做各的,导致各类核心数据分散于各个业务组。8月初资源整合方案落地并开始实施,我们组承担起了管控各类数据的任务,未来各业务组生产出的数据以及各业务组需要的数据都只有我们这一个入口。

由于涉及到不同类的数据,并且这些数据是分散在各个业务组不同项目的数据库中,而且迁移产生的逻辑代码也是临时性,写在不同的项目或写在某一项目中也不合理,所以我想到的是用最初的项目框架搭建一个新的项目,使用多数据源,直接访问各个项目的数据库获取源数据,也不需要其他项目组做什么配合工作,数据交接工作只需要给我们梳理清除各个表的关系即可,后续迁移完新项目也直接停止服务即可。

所以接下来写一篇总结,Spring Cloud框架中如何配置多数据源。其实和Spring Boot项目配置一样,只是Spring Cloud框架数据源切换的切面定义有所不同。

快速开始

1. Maven依赖

<dependency><groupId>com.zaxxer</groupId><artifactId>HikariCP</artifactId><version>3.2.0</version>
</dependency>
<dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>5.1.10.RELEASE</version>
</dependency>
<dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.13</version>
</dependency>

以上依赖主要是数据库相关的,Spring Cloud相关的依赖就不在这展示了,涉及的依赖包括像nacos注册中心、feign、ribbon等等。

2. 数据库类型定义

首先,把需要访问的所有数据库用一个枚举来定义,下面就用英文1-4表示4个不同的数据库。

其次,提供设置与访问数据源类型的方案,为切面设置不同的数据源使用。

public class DataSourceType {/*** 数据库类型*/public enum DataBaseType {/*** 数据库1*/one,/*** 数据库2*/two,/*** 数据库3*/three,/*** 数据库4*/four}/*** 使用ThreadLocal保证线程安全*/private static final ThreadLocal<DataBaseType> TYPE = new ThreadLocal<>();/*** 往当前线程里设置数据源类型** @param dataBaseType 数据源类型*/public static void setDataBaseType(DataBaseType dataBaseType) {if (dataBaseType == null) {throw new NullPointerException();}TYPE.set(dataBaseType);}/*** 获取数据源类型** @return 返回数据源的类型*/public static DataBaseType getDataBaseType() {//默认使用数据库1return TYPE.get() == null ? DataBaseType.one : TYPE.get();}/*** 清空数据类型*/public static void clearDataBaseType() {TYPE.remove();}
}

3. 数据库配置

在配置文件中添加各个数据库的连接地址、用户名和密码等信息。

spring:datasource:one:driver-class-name: com.mysql.cj.jdbc.Driverjdbc-url: ****username: ****password: ****queryTimeout: 10000two:driver-class-name: com.mysql.cj.jdbc.Driverjdbc-url: ****username: ****password: ****queryTimeout: 10000three:driver-class-name: com.mysql.cj.jdbc.Driverjdbc-url: ****username: ****password: ****queryTimeout: 10000four:driver-class-name: com.mysql.cj.jdbc.Driverjdbc-url: ****username: ****password: ****queryTimeout: 10000

4. 多数据源核心配置类

@Configuration
//若扫描不到mapper,添加以下注解配置基础包即可
@MapperScan(basePackages = "XXX", sqlSessionFactoryRef = "SqlSessionFactory")
public class DataSourceConfig {@Primary@Bean(name = "oneDataSource")@ConfigurationProperties(prefix = "spring.datasource.one")public DataSource getOneDateSource() {return DataSourceBuilder.create().build();}@Bean(name = "twoDataSource")@ConfigurationProperties(prefix = "spring.datasource.two")public DataSource getTwoDateSource() {return DataSourceBuilder.create().build();}@Bean(name = "threeDataSource")@ConfigurationProperties(prefix = "spring.datasource.three")public DataSource getThreeDateSource() {return DataSourceBuilder.create().build();}@Bean(name = "fourDataSource")@ConfigurationProperties(prefix = "spring.datasource.four")public DataSource getFourDateSource() {return DataSourceBuilder.create().build();}/*** 装载多个数据库源** @param oneDataSource* @param twoDataSource* @param threeDataSource* @param fourDataSource* @return 返回数据源集合*/@Bean(name = "dynamicDataSource")public DynamicDataSource dataSource(@Qualifier("oneDataSource") DataSource oneDataSource,@Qualifier("twoDataSource") DataSource twoDataSource,@Qualifier("threeDataSource") DataSource threeDataSource,@Qualifier("fourDataSource") DataSource fourDataSource) {Map<Object, Object> targetDataSource = new HashMap<>(16);targetDataSource.put(DataSourceType.DataBaseType.one, oneDataSource);targetDataSource.put(DataSourceType.DataBaseType.two, twoDataSource);targetDataSource.put(DataSourceType.DataBaseType.three, threeDataSource);targetDataSource.put(DataSourceType.DataBaseType.four, fourDataSource);DynamicDataSource dataSource = new DynamicDataSource();dataSource.setTargetDataSources(targetDataSource);//默认数据源dataSource.setDefaultTargetDataSource(oneDataSource);return dataSource;}/*** 装配数据源添加扫描mapper.xml文件的路径位置** @param dynamicDataSource 多数据库源对象* @return 返回sql会话工厂*/@Bean(name = "SqlSessionFactory")public SqlSessionFactory setSqlSessionFactory(@Qualifier("dynamicDataSource") DataSource dynamicDataSource) throws Exception {// 导入mybatis sql session配置MybatisSqlSessionFactoryBean sessionFactory = new MybatisSqlSessionFactoryBean();// 指明数据源sessionFactory.setDataSource(dynamicDataSource);// 指明mapper.xml位置(配置文件中指明的xml位置会失效用此方式代替,具体原因未知)
//        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:/mapper/**/*Mapper.xml"));// 指明实体扫描(多个package用逗号或者分号分隔)sessionFactory.setTypeAliasesPackage("XXX");// 导入mybatis配置MybatisConfiguration configuration = new MybatisConfiguration();configuration.setJdbcTypeForNull(JdbcType.NULL);configuration.setMapUnderscoreToCamelCase(true);configuration.setCacheEnabled(false);// 配置打印sql语句configuration.setLogImpl(StdOutImpl.class);// 添加分页功能configuration.addInterceptor(new PaginationInterceptor());sessionFactory.setConfiguration(configuration);return sessionFactory.getObject();}/*** 注入事务管理*/@Beanpublic DataSourceTransactionManager transactionManager(DynamicDataSource dynamicDataSource) {return new DataSourceTransactionManager(dynamicDataSource);}
}

5. 数据源切面

核心思想就是AOP,通过访问不同路径的包,做数据源切换。在Spring Cloud框架中,主要是通过不同的feign包来区分使用哪个数据源。

@Aspect
@Component
public class DataSourceAop {/*** 设定切面地址在所有调用以下包下的任意类的任意方法或接口时切换数据源成指定数据源*/@Before("execution(* com.XXX.feign.impl.one..*(..))")public void setDataSourceOne() {DataSourceType.setDataBaseType(DataSourceType.DataBaseType.one);}@Before("execution(* com.XXX.feign.impl.two..*(..))")public void setDataSourceTwo() {DataSourceType.setDataBaseType(DataSourceType.DataBaseType.two);}@Before("execution(* com.XXX.feign.impl.three..*(..))")public void setDataSourceThree() {DataSourceType.setDataBaseType(DataSourceType.DataBaseType.three);}@Before("execution(* com.XXX.feign.impl.four..*(..))")public void setDataSourceFour() {DataSourceType.setDataBaseType(DataSourceType.DataBaseType.four);}
}

以上就是Spring Cloud框架的步骤及核心代码。

总结

从结果来看,当初用一个独立的项目配置多数据源还是非常正确的选择。因为各项目难免有不同的需求仍然在不断开发迭代中,迁移这项任务涉及多个项目本来就很复杂,所以这个多数据源项目还是起到了很大的帮助作用的。

【Spring Cloud】多数据源配置相关推荐

  1. spring cloud config将配置存储在数据库中

    点击上方"方志朋",选择"置顶或者星标" 你的关注意义重大! Spring Cloud Config Server最常见是将配置文件放在本地或者远程Git仓库, ...

  2. spring cloud config将配置存储在数据库中 1

    转载请标明出处: https://blog.csdn.net/forezp/... 本文出自方志朋的博客 Spring Cloud Config Server最常见是将配置文件放在本地或者远程Git仓 ...

  3. Spring Cloud Config的配置中心获取不到最新配置信息的问题

    本篇源于Spring Cloud Config的一个问题,但这个问题并非所有人都会遇到.如果您遇到了,那必须得看看这篇,如果没有遇到您也应该看看,防患于未然! 问题描述 之前有朋友提出Spring C ...

  4. spring cloud Eureka 之配置信息

    转载来源:http://blog.51cto.com/881206524/2117014 spring cloud Eureka 之配置信息 Eureka instance 一个服务,如:订单系统,会 ...

  5. Spring实现多数据源配置

    一.前言 对于小型项目,服务器与数据库是可以在同一台机子上的,但随着业务的庞大与负责,数据库和服务器就会分离开来.同时随着数据量的增大,数据库也要分开部署到多台机子上. 二.Spring配置文件修改 ...

  6. spring mybatis 多数据源配置 jeesite 多数据源配置

    spring mybatis 多数据源配置 jeesite 多数据源配置 一.情景描述 在系统数据达到一定的访问量时,遇到单个数据库瓶颈,所以需要扩展数据库,启用第二个数据源资源,项目架构变成 一个服 ...

  7. spring boot多数据源配置示例

    spring boot多数据源配置 1.application.properties spring.datasource.url = jdbc\:oracle\:thin\:@192.168.3.88 ...

  8. 第十二章 Spring Cloud Config 统一配置中心详解

    目录 一.配置问题分析及解决方案 1.问题分析 2.解决方案 二.Spring Cloud Config 介绍 1.Spring Cloud Config特性 2.Spring Cloud Confi ...

  9. spring+druid多数据源配置

    博客引用处(以下内容在原有博客基础上进行补充或更改,谢谢这些大牛的博客指导): spring+druid多数据源配置 druid多数据源配置 一.druid简介 Druid首先是一个数据库连接池,但它 ...

  10. Spring Cloud第八篇:Spring Cloud Bus刷新配置

    Spring Cloud Bus 将分布式的节点用轻量的消息代理连接起来.它可以用于广播配置文件的更改或者服务之间的通讯,也可以用于监控.本文要讲述的是用Spring Cloud Bus实现通知微服务 ...

最新文章

  1. 2021阿里技术人的成长路径!
  2. 在Android工程中加入AIDL文件时,gen目录生成的文件报错-问题解决
  3. pythondjango图书_Django基础教程
  4. 为什么大型科技公司更会发生人员流失 标准 ceo 软件 技术 图 阅读2479 原文:Why Good People Leave Large Tech Companies 作者:steve
  5. ToString() 会发生装箱吗?
  6. android 4.x环境搭建
  7. 基于Element ui 实现输入框只能输入数字并支持千分位
  8. JavaWeb入门之简单分页查询功能实现
  9. 使用解码逻辑创建YOLO Core ML对象检测器(四)
  10. mysql每天1点执行存储过程_一天一点MySQL复习——存储过程
  11. Firefox国际版上登录本地服务
  12. 设计模式(一) 简单工厂模式
  13. 计算机硬件的五大逻辑部分,计算机的硬件系统由五大部分组成(计算机由几部分组成)...
  14. 【游戏测试】bug优先级的定义及如何描述
  15. 【C语言进阶】预定义详解
  16. ssh和telnet客户软件ZOC如何设置UTF-8
  17. libpng warning: iCCP: known incorrect sRGB profile 警告,问题解决
  18. 安卓10不支持qmc解码_Root神器支持安卓10 面具Magisk v20.4+Magisk Manager v7.5.1
  19. Matlab中的clc、clear、clear all、clf、close、close all解释
  20. android 坚挺通话广播_安卓版本最新占比 Android 4.4很坚挺

热门文章

  1. Sony Vegas使用记录
  2. python线程和进程
  3. STM32 超声波测距模块HC-SR04 驱动
  4. 怎么更新opengl.dll文件_安装累积更新丢文件似乎已成为惯例 KB4556799同样出现文件丢失问题...
  5. PCL安装教程 1.8.0+VS2013+cmake+QT5.5.1
  6. 安卓开发——微信UI界面
  7. HTML-动画实现Animation
  8. SAP如何判断物料主数据中哪些视图有维护,哪些没有维护?
  9. 2019深信服笔试 —— 猎人抓兔子
  10. oracle日志保存时间设置,关于日志设置的详细介绍