作者平台:
| 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: share
datasource:
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=true
username: root
password: jiang
driver-class-name: com.mysql.cj.jdbc.Driver
db2:
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=true
username: root
password: jiang
driver-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;
}
@Override
public 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 {
@Autowired
DepartmentDao departmentDao;
@Override
public Department findByID(int id) {
return departmentDao.findById(id);
}
}
复制代码
然后就是controller:
@RestController
@RequestMapping(value = "/do/department")
public class DepartmentController {
@Autowired
DepartmentService 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的生命周期中自定义初始化和销毁方法的四种方式