SpringBoot多数据源配置
作者平台:
| CSDN:blog.csdn.net/qq_41153943
| 掘金:juejin.cn/user/651387…
| 知乎:www.zhihu.com/people/1024…
| GitHub:github.com/JiangXia-10…
| 微信公众号:1024笔记
本文大约6171字,预计阅读时长16分钟
前言
在实际的开发或者线上环境中,一般都不仅仅是一个数据库走天下,而是根据业务进行拆分多个数据库,今天就来学习如何对springboot进行多数据源配置。
本文的工程基础是之前的项目工程,具体可以参考SpringBoot整合Redis使用教程。项目源码最后也会同步只github。地址在最后,欢迎下载star!
正文
数据库
首先准备下数据库:这里有两个数据库,一个是test数据库,里面有个user表,数据如下:
/*
Source Server : testdb
Source Host : localhost:3306
Source Database : test
Target Server Type : MYSQL
Date: 2021-12-09 10:51:21
*/
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (`id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID',`email` varchar(255) NOT NULL COMMENT '邮箱',`password` varchar(255) NOT NULL COMMENT '密码',`username` varchar(255) NOT NULL COMMENT '姓名',PRIMARY KEY (`id`),UNIQUE KEY `email` (`email`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', 'liqing@lol.com', '123456', '李青');
INSERT INTO `user` VALUES ('2', 'daome@lol.com', '234567', '刀妹');
INSERT INTO `user` VALUES ('3', 'yasuo@lol.com', '345678', '亚索');复制代码
接着有个spring_cache数据库,并且里面有个department表,数据如下:
/*
Source Server : testdb
Source Server Version : 50527
Source Host : localhost:3306
Source Database : spring_cache
Date: 2021-12-09 11:32:16
*/SET FOREIGN_KEY_CHECKS=0;
DROP TABLE IF EXISTS `department`;
CREATE TABLE `department` (`id` int(11) NOT NULL AUTO_INCREMENT,`departmentName` varchar(255) DEFAULT NULL,PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;-- ----------------------------
-- Records of department
-- ----------------------------
INSERT INTO `department` VALUES ('1', '中路部门');
INSERT INTO `department` VALUES ('2', '打野部门');
INSERT INTO `department` VALUES ('3', '上路部门');
复制代码
代码
首先需要在application.yml配置文件中配置两个数据源配置,分别为db1,b2,具体配置如下:
spring:application:name: sharedatasource:dynamic:primary: db1 # 配置默认数据库db1:jdbc-url: jdbc:mysql://localhost:3306/test?serverTimezone=Asia/Chongqing&useUnicode=true&characterEncoding=utf8&characterSetResults=utf8&useSSL=false&verifyServerCertificate=false&autoReconnct=true&autoReconnectForPools=true&allowMultiQueries=trueusername: rootpassword: jiangdriver-class-name: com.mysql.cj.jdbc.Driverdb2:jdbc-url: jdbc:mysql://localhost:3306/spring_cache?serverTimezone=Asia/Chongqing&useUnicode=true&characterEncoding=utf8&characterSetResults=utf8&useSSL=false&verifyServerCertificate=false&autoReconnct=true&autoReconnectForPools=true&allowMultiQueries=trueusername: rootpassword: jiangdriver-class-name: com.mysql.cj.jdbc.Driver
复制代码
因为这里采用的是之前工程的代码,所以关于另一个数据源相关的代码这里不贴了,这里主要写新增数据源的代码逻辑,之前的可以的参考之前的文章,或者github下载源码,地址贴在最后。
在bean文件夹下声明一个department实体类,如下:
public class Department {public Integer id;public String departmentName;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getDepartmentName() {return departmentName;}public void setDepartmentName(String departmentName) {this.departmentName = departmentName;}public Department(Integer id, String departmentName) {this.id = id;this.departmentName = departmentName;}@Overridepublic String toString() {return "Department{" +"id=" + id +", departmentName='" + departmentName + '\'' +'}';}
}
复制代码
然后新增一个dao文件:
public interface DepartmentDao {/*** 根据查询数据**/@Select("select id,departmentName from department where id=#{id}")Department findById(@Param("id") int id);
}
复制代码
service和serviceimpl如下:
public interface DepartmentService {//根据id查询部门Department findByID(int id);
}
复制代码
@Service
public class DepartmentServiceImpl implements DepartmentService {@AutowiredDepartmentDao departmentDao;@Overridepublic Department findByID(int id) {return departmentDao.findById(id);}
}
复制代码
然后就是controller:
@RestController
@RequestMapping(value = "/do/department")
public class DepartmentController {@AutowiredDepartmentService departmentService;//根据用户名查询数据@RequestMapping(value = "/dep", method = RequestMethod.GET)public Department department(@RequestParam(value = "id",required = true) int id){return departmentService.findByID(id);}
}
复制代码
最后写一个关于数据源的配置文件,具体如下:
@Configuration
@MapperScan(basePackages = "com.springboot.springbootdemo.dao.db1",sqlSessionFactoryRef = "db1SqlSessionFactory")
public class DB1DataSourceConfig {static final String MAPPER_LOCATION = "classpath:/mapping/db1/*.xml";@Bean("db1DataSource")@ConfigurationProperties(prefix = "spring.datasource.db1")public DataSource getDb1DataSource(){return DataSourceBuilder.create().build();}@Bean("db1SqlSessionFactory")public SqlSessionFactory db1SqlSessionFactory(@Qualifier("db1DataSource") DataSource dataSource) throws Exception {SqlSessionFactoryBean bean = new SqlSessionFactoryBean();bean.setDataSource(dataSource);bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(MAPPER_LOCATION));return bean.getObject();}@Bean("db1SqlSessionTemplate")public SqlSessionTemplate db1SqlSessionTemplate(@Qualifier("db1SqlSessionFactory") SqlSessionFactory sqlSessionFactory){return new SqlSessionTemplate(sqlSessionFactory);}
}
复制代码
@Configuration
@MapperScan(basePackages ="com.springboot.springbootdemo.dao.db2",sqlSessionFactoryRef = "db2SqlSessionFactory")
public class DB2DataSourceConfig {static final String MAPPER_LOCATION = "classpath:/mapping/db2/*.xml";@Bean("db2DataSource")@ConfigurationProperties(prefix = "spring.datasource.db2")public DataSource getDb1DataSource(){return DataSourceBuilder.create().build();}@Bean("db2SqlSessionFactory")public SqlSessionFactory db1SqlSessionFactory(@Qualifier("db2DataSource") DataSource dataSource) throws Exception {SqlSessionFactoryBean bean = new SqlSessionFactoryBean();bean.setDataSource(dataSource);bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(MAPPER_LOCATION));return bean.getObject();}@Bean("db2SqlSessionTemplate")public SqlSessionTemplate db1SqlSessionTemplate(@Qualifier("db2SqlSessionFactory") SqlSessionFactory sqlSessionFactory){return new SqlSessionTemplate(sqlSessionFactory);}
}
复制代码
测试
以上步骤完毕之后进行测试,启动项目成功之后,首先在地址栏输入:
http://localhost:8081/share/do/user/userAll
复制代码
查询db1数据库的数据,结果如下:
接着查询db2数据库的数据,地址栏输入:
http://localhost:8081/share/do/department/dep?id=1
复制代码
结果如下:
可见通过以上配置,能够实现springboot的多数据源配置效果。
总结
springboot配置多数据源其实很简单,首先在application配置文件中配置多个数据源的配置,然后有几个数据源就写几个数据源的配置类即可。本项目的工程结构如下:
最后resource文件夹下的mapping文件下的*.Mapper.xml,可以没有具体的逻辑,但是结构文件得有,不然会报错。在数据源的配置类中的MAPPER_LOCATION有使用到!
如有任何问题或者不对的地方欢迎一起交流讨论学习!
本项目源码在:
github.com/JiangXia-10…
欢迎下载、Star!
相关推荐
Spring注解(三):@scope设置组件作用域
Spring常用注解大全,值得你的收藏!!!
Spring注解(七):使用@Value对Bean进行属性赋值
SpringBoot开发Restful风格的接口实现CRUD功能
Spring注解(六):Bean的生命周期中自定义初始化和销毁方法的四种方式
SpringBoot多数据源配置相关推荐
- Springboot多数据源配置详解
Springboot多数据源配置详解 概念 配置 多数据源使用 概念 一般来说,我们正常的业务只涉及一个数据源,在特定的业务场景中需要使用多个数据源的情况,就需要配置多个数据源来满足特定的业务需求.本 ...
- springboot 多数据源配置的几种方式
springboot多数据源配置的三种方式 application.yml配置 1.@Ds("配置数据源名称") 引入依赖 <dependency> <group ...
- java spring多数据源配置文件_基于注解实现SpringBoot多数据源配置
1.功能介绍 在实际的开发中,同一个项目中使用多个数据源是很常见的场景.最近在学习的过程中使用注解的方式实现了一个Springboot项目多数据源的功能.具体实现方式如下. 2.在applicatio ...
- SpringBoot 之数据源配置
文章目录 市面上的几种数据源比对 SpringBoot自动装配DataSource原理 HiKariCP 数据源配置 Druid 数据源配置 SpringBoot集成Druid连接池 Druid 多数 ...
- SpringBoot排除数据源配置,配置决定行为
项目场景: 最近接到一个需求,大概意思呢就是数据库连接不够用了,部分服务(分服务)就不需要配置数据源了,需要跟db打交道的地方全部改成rpc去调用具备db能力的服务(总服务) 问题描述: 其实需要改的 ...
- springboot 多数据源配置,postgresql+mysql为例
由于项目需要,利用springboot配置多数据源,postgresql+mysql: 1.首先导入需要的依赖包,包的版本根据需要选择,本项目是spring-boot-starter-parent 2 ...
- springBoot 双数据源配置 (Oracle+ SQL sever)主数据源配置setMapperLocations多个路径
1.添加pom依赖 (部分) <!--添加 阿里连接池 支持--><dependency><groupId>com.alibaba</groupId>& ...
- springboot 多数据源配置与使用
多数据源配置 这个是springboot1版本的 spingboot2移步 > springboot2.x jpa接入多数据源 application.properties 配置两个数据库 #数 ...
- springboot多数据源配置_SpringBoot-配置多数据源
1.4.springboot整合多数据源 你们在项目中有使用到多数据源吗? 4.4.1配置文件中新增两个数据源 spring.datasource.test1.driverClassName = co ...
最新文章
- php日期选择插件,优雅的日期选择插件daterangepicker
- ATS中的命令行工具解读
- 单元、集成、系统、验收测试比较
- SunDay天气——开放源代码
- lucene全文搜索之三:生成索引字段,创建索引文档(给索引字段加权)基于lucene5.5.3...
- .NET Core 3.0 webapi集成Swagger 5.0
- linux使用设备文件的目录,Linux系统下的/dev目录
- 图嵌入综述 (arxiv 1709.07604) 译文 4.1 ~ 4.2
- linux挂载磁盘没有权限,linux肿么知道哪个盘没有被挂载
- 爬取百万github用户数据,查找谁才是python大牛?
- 一元二次方程abc决定什么_情绪管理 - ABC理论
- 异步读写之利用完成历程
- 需求分析和架构设计总结--利用DODAF方法
- multisim安装完成后显示安装程序损坏的免费解决方案
- 使用python爬取百度今日热点事件排行榜
- 逻辑电路是计算机学的吗,下列属于组合逻辑电路的是( )。
- Vue:v-charts图表设置指标别名
- 初识C语言:了解基础指针
- c++海盗战争1.0正式版【免费复制】
- mysql 分表 id_MySQL分表自增ID解决方案
热门文章
- GitHub 智能编程助手 GPT-4 Copilot X 震撼来袭!动动嘴,AI 就能帮你生成代码
- python pad_图文并茂的Python教程-numpy.pad
- coreldraw制造立体视频冲击效果字体
- IT高薪者所具备的人格魅力【转】
- CSDN 转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(已有图床)
- ffmpeg静态库的裁剪
- DMU-参数介绍-学习笔记1
- php获取中国银行汇率,用Simple Html Dom Parser 获取中国银行汇率
- Windows搜索的探索-----001
- 面向工业物联网的无线传感器网络