SpringBoot多数据源配置

本文涉及的产品
云数据库 RDS MySQL,集群版 2核4GB 100GB
推荐场景:
搭建个人博客
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS MySQL,高可用版 2核4GB 50GB
简介: 在实际的开发或者线上环境中,一般都不仅仅是一个数据库走天下,而是根据业务进行拆分多个数据库,今天就来学习如何对springboot进行多数据源配置。

前言


在实际的开发或者线上环境中,一般都不仅仅是一个数据库走天下,而是根据业务进行拆分多个数据库,今天就来学习如何对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数据库的数据,结果如下:


微信截图_20220521212438.png


接着查询db2数据库的数据,地址栏输入:


http://localhost:8081/share/do/department/dep?id=1
复制代码


结果如下:


692d934cfe4b4e788aed5ff5dc9e2ccb~tplv-k3u1fbpfcp-zoom-in-crop-mark_1304_0_0_0.webp.jpg


可见通过以上配置,能够实现springboot的多数据源配置效果。


总结


springboot配置多数据源其实很简单,首先在application配置文件中配置多个数据源的配置,然后有几个数据源就写几个数据源的配置类即可。本项目的工程结构如下:


5da973b179b645a69c0c488739979087~tplv-k3u1fbpfcp-zoom-in-crop-mark_1304_0_0_0.webp.jpg


最后resource文件夹下的mapping文件下的*.Mapper.xml,可以没有具体的逻辑,但是结构文件得有,不然会报错。在数据源的配置类中的MAPPER_LOCATION有使用到!


如有任何问题或者不对的地方欢迎一起交流讨论学习!

相关实践学习
如何在云端创建MySQL数据库
开始实验后,系统会自动创建一台自建MySQL的 源数据库 ECS 实例和一台 目标数据库 RDS。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助     相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
目录
相关文章
|
5天前
|
Java 应用服务中间件 开发者
Java面试题:解释Spring Boot的优势及其自动配置原理
Java面试题:解释Spring Boot的优势及其自动配置原理
28 0
|
24天前
|
druid Java 关系型数据库
Spring Boot2 系列教程(二十五)Spring Boot 整合 Jpa 多数据源
Spring Boot2 系列教程(二十五)Spring Boot 整合 Jpa 多数据源
|
10天前
|
Java
no main manifest attribute,软件开发部署SpringBoot要填配置,不填配置,报错哦@_@
no main manifest attribute,软件开发部署SpringBoot要填配置,不填配置,报错哦@_@
|
12天前
|
XML Java 关系型数据库
Action:Consider the following: If you want an embedde ,springBoot配置数据库,补全springBoot的xml和mysql配置信息就好了
Action:Consider the following: If you want an embedde ,springBoot配置数据库,补全springBoot的xml和mysql配置信息就好了
|
11天前
|
开发框架 Java 数据库
Spring Boot集成多数据源的最佳实践
Spring Boot集成多数据源的最佳实践
|
12天前
|
Java 测试技术 Spring
支付系统15-----支付宝支付,引入支付参数,如何使支付宝的配置信息变成SpringBoot相关的配置信息
支付系统15-----支付宝支付,引入支付参数,如何使支付宝的配置信息变成SpringBoot相关的配置信息
|
12天前
|
Java 数据库连接 mybatis
SpringBoot配置Mybatis注意事项,mappers层下的name命名空间,要落实到Dao的video类,resultType要落到bean,配置好mybatis的对应依赖。
SpringBoot配置Mybatis注意事项,mappers层下的name命名空间,要落实到Dao的video类,resultType要落到bean,配置好mybatis的对应依赖。
|
20天前
|
缓存 Java 数据库
springboot数据库及缓存常用依赖及配置
springboot数据库及缓存常用依赖及配置
46 9
|
21天前
|
存储 缓存 NoSQL
SpringBoot配置第三方专业缓存框架j2cache
SpringBoot配置第三方专业缓存框架j2cache
25 5
|
21天前
|
存储 缓存 NoSQL
SpringBoot配置第三方专业缓存技术Redis
SpringBoot配置第三方专业缓存技术Redis
20 4