SpringBoot搭建多数据源的实现方法
首先我们建立两个数据库(可以不在同一台电脑上):
multiple_order
:
DROP DATABASE IF EXISTS `multiple_order`;
CREATE DATABASE `multiple_order`;
USE `multiple_order`;
CREATE TABLE `order` (
`order_id` BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT COMMENT '订单id',
`user_id` BIGINT UNSIGNED NOT NULL COMMENT '用户id',
`cost` DECIMAL(13, 2) COMMENT '订单费用'
) COMMENT '订单表';
multiple_user
:
DROP DATABASE IF EXISTS `multiple_user`;
CREATE DATABASE `multiple_user`;
USE `multiple_user`;
CREATE TABLE `user` (
`user_id` BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT COMMENT '用户id',
`username` VARCHAR(50) NOT NULL COMMENT '用户名',
`age` TINYINT UNSIGNED COMMENT '年龄'
) COMMENT '用户表';
然后创建一个maven项目,其中 pom.xml
文件:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<!-- SpringBoot的夫项目 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.9.RELEASE</version>
</parent>
<groupId>love.xiaohh.datasource</groupId>
<artifactId>multiple-datasources</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<!-- SpringMVC 相关的依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring 健康检测模块 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!-- mybatis 相关依赖 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
<!-- MySQL 驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- json 工具类 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.78</version>
</dependency>
</dependencies>
<build>
<plugins>
<!-- 制作一个可运行的 jar 包需要的插件 -->
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
在 application.yml
中需要配置两个数据源:
spring:
datasource:
# 用户模块数据库配置
user:
driver-class-name: com.mysql.cj.jdbc.Driver
jdbc-url: jdbc:mysql://127.0.0.1:3306/multiple_user?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
username: root
password: xiaohh
# 订单模块数据库配置
order:
driver-class-name: com.mysql.cj.jdbc.Driver
jdbc-url: jdbc:mysql://127.0.0.1:3306/multiple_order?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
username: root
password: xiaohh
mybatis:
# Mapper 的目录
mapper-locations: classpath:mapper*Mapper.xml
然后我们定义一个配置类 DataSourseConfig
用于配置多数据源,首先是申明数据源,按照 application.yml
当中的配置定义两个数据源,注意当中的DataSource 是 javax.sql.DataSource
:
@Primary // 需要一个默认配置的数据源
@Bean("user")
@ConfigurationProperties(prefix = "spring.datasource.user") // 在yml中配置数据源的前缀
public DataSource user() {
return DataSourceBuilder.create().build();
}
@Bean("order")
@ConfigurationProperties(prefix = "spring.datasource.order") // 在yml中配置数据源的前缀
public DataSource order() {
return DataSourceBuilder.create().build();
}
然后创建 SqlSessionFactory
:
@Primary // 配置一个这个类型默认的 bean
@Bean("userSqlSessionFactory")
public SqlSessionFactory userSqlSessionFactory(@Qualifier("user") DataSource user) throws Exception {
// 创建bean
SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
// 设置数据源
factory.setDataSource(user);
// 设置 mapper 文件的扫描
factory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/user
@Bean("orderSqlSessionFactory")
public SqlSessionFactory orderSqlSessionFactory(@Qualifier("order") DataSource order) throws Exception {
// 创建bean
SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
// 设置数据源
factory.setDataSource(order);
// 设置 mapper 文件的扫描
factory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/order
@Primary // 设置这个类型默认的 bean
@Bean("userSqlSessionTemplate")
public SqlSessionTemplate userSqlSessionTemplate(@Qualifier("userSqlSessionFactory") SqlSessionFactory userSqlSessionFactory) {
return new SqlSessionTemplate(userSqlSessionFactory);
}
@Bean("orderSqlSessionTemplate")
public SqlSessionTemplate orderSqlSessionTemplate(@Qualifier("orderSqlSessionFactory") SqlSessionFactory orderSqlSessionFactory) {
return new SqlSessionTemplate(orderSqlSessionFactory);
}
最后别忘了在配置类上加上一个注解,用于声明哪些Mapper文件用哪些注解:
@Configuration
@MapperScans({
// basePackages 是mapper的包路径,sqlSessionTemplateRef 是指定我们创建的 SqlSessionTemplate
@MapperScan(basePackages = "love.xiaohh.datasource.mapper.user", sqlSessionTemplateRef = "userSqlSessionTemplate"),
@MapperScan(basePackages = "love.xiaohh.datasource.mapper.order", sqlSessionTemplateRef = "orderSqlSessionTemplate")
})
完整的 DataSourceConfig
类的代码:
package love.xiaohh.datasource.config;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.annotation.MapperScans;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import javax.sql.DataSource;
@Configuration
@MapperScans({
// basePackages 是mapper的包路径,sqlSessionTemplateRef 是指定我们创建的 SqlSessionTemplate
@MapperScan(basePackages = "love.xiaohh.datasource.mapper.user", sqlSessionTemplateRef = "userSqlSessionTemplate"),
@MapperScan(basePackages = "love.xiaohh.datasource.mapper.order", sqlSessionTemplateRef = "orderSqlSessionTemplate")
})
public class DataSourceConfig {
@Primary // 需要一个默认配置的数据源
@Bean("user")
@ConfigurationProperties(prefix = "spring.datasource.user") // 在yml中配置数据源的前缀
public DataSource user() {
return DataSourceBuilder.create().build();
}
@Bean("order")
@ConfigurationProperties(prefix = "spring.datasource.order") // 在yml中配置数据源的前缀
public DataSource order() {
return DataSourceBuilder.create().build();
}
@Primary // 配置一个这个类型默认的 bean
@Bean("userSqlSessionFactory")
public SqlSessionFactory userSqlSessionFactory(@Qualifier("user") DataSource user) throws Exception {
// 创建bean
SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
// 设置数据源
factory.setDataSource(user);
// 设置 mapper 文件的扫描
factory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/user
@Bean("orderSqlSessionFactory")
public SqlSessionFactory orderSqlSessionFactory(@Qualifier("order") DataSource order) throws Exception {
// 创建bean
SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
// 设置数据源
factory.setDataSource(order);
// 设置 mapper 文件的扫描
factory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/order
@Primary // 设置这个类型默认的 bean
@Bean("userSqlSessionTemplate")
public SqlSessionTemplate userSqlSessionTemplate(@Qualifier("userSqlSessionFactory") SqlSessionFactory userSqlSessionFactory) {
return new SqlSessionTemplate(userSqlSessionFactory);
}
@Bean("orderSqlSessionTemplate")
public SqlSessionTemplate orderSqlSessionTemplate(@Qualifier("orderSqlSessionFactory") SqlSessionFactory orderSqlSessionFactory) {
return new SqlSessionTemplate(orderSqlSessionFactory);
}
}
然后按照注解上面定义的包创建两个 Mapper 接口
OrderMapper
:
package love.xiaohh.datasource.mapper.order;
import love.xiaohh.datasource.entities.order.Order;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface OrderMapper {
int insertOrder(Order order);
List<Order> selectOrder(Order order);
}
UserMapper
:
package love.xiaohh.datasource.mapper.user;
import love.xiaohh.datasource.entities.user.User;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface UserMapper {
int insertUser(User user);
List<User> selectUser(User user);
}
之后我会将代码提交到 gitee,所以 Mapper.xml、Controller、Service 代码在此处省略,然后我们新增几条用户数据:
查询一下:
同时订单数据库:
查询:
然后在数据库当中查看是否是发送到不同的数据库:
可以确定,确实是存入了两个数据库。好了下课
代码仓库
:https://gitee.com/xiaohha/multiple-datasources
到此这篇关于SpringBoot搭建多数据源的实现方法的文章就介绍到这了,更多相关SpringBoot搭建多数据源内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341