springboot中多数据源配置和使用
最佳答案 问答题库998位专家为你答疑解惑
在日常开发中有时候会涉及到多个数据库的连接和使用,如果项目是使用微服务部署,可以通过增加一个服务来处理数据库连接,如果项目是单体的,这时候就要考虑多数据源的配置了,在springboot中多数据源的配置相对来说还是很简单的,通过几个步骤就可以实现多数据源连接和使用。
项目只使用了mybatis框架,为了演示最原始的配置这里就没有使用mybatis-plus。引入依赖如下:
<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.6.11</version><relativePath/>
</parent><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jdbc</artifactId></dependency><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.1.2</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.48</version></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.12</version><scope>provided</scope></dependency>
</dependencies>
接下来就需要在 application.yaml
中做一些配置:
server:port: 8081shutdown: gracefulspring:application:name: test-dbjackson:date-format: yyyy-MM-dd HH:mm:sstime-zone: GMT+8locale: zh_CNdatasource:db1: # 设置数据源1jdbc-url: jdbc:mysql://127.0.0.1:3306/db1?allowMultiQueries=true&useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8driver-class-name: com.mysql.jdbc.Driverusername: rootpassword: 123456@Testhikari:auto-commit: true # 自动提交connection-timeout: 30000 # 连接超时时间idle-timeout: 30000 # 连接池空闲连接回收时间minimum-idle: 1 # 最小链接数maximum-pool-size: 4 # 最大连接数max-lifetime: 1800000 # 线程最大存活时间connection-test-query: SELECT A FROM T_POOLPING # 配置检查连接db2: # 设置数据源2jdbc-url: jdbc:mysql://127.0.0.1:3306/db2?allowMultiQueries=true&useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8driver-class-name: com.mysql.jdbc.Driverusername: rootpassword: 123456@Testhikari:auto-commit: true # 自动提交connection-timeout: 30000 # 连接超时时间idle-timeout: 30000 # 连接池空闲连接回收时间minimum-idle: 1 # 最小链接数maximum-pool-size: 8 # 最大连接数max-lifetime: 1800000 # 线程最大存活时间connection-test-query: SELECT A FROM T_POOLPING # 配置检查连接
在上面的datasource节点下增加了两个子配置db1和db2,分别表示两个数据源,接下来要设置两个数据源的配置:
数据源1的配置:
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
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 org.springframework.jdbc.datasource.DataSourceTransactionManager;import javax.sql.DataSource;/*** 数据源1配置** @Author xingo* @Date 2023/11/8*/
@Configuration
@MapperScan(basePackages = "org.example.mapper.db1", sqlSessionTemplateRef = "db1SqlSessionTemplate")
public class Db1SourceConfig {/*** 第一个数据源配置* @return*/@Bean(name="db1Source")@ConfigurationProperties(prefix = "spring.datasource.db1")@Primarypublic DataSource dataSource() {return DataSourceBuilder.create().build();}/*** 第一个数据源的会话工厂配置* @param dataSource* @return* @throws Exception*/@Bean(name = "db1SqlSessionFactory")@Primarypublic SqlSessionFactory sqlSessionFactory(@Qualifier("db1Source") DataSource dataSource) throws Exception {SqlSessionFactoryBean bean = new SqlSessionFactoryBean();bean.setDataSource(dataSource);// 指定扫描sql语句xml文件路径bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/db1/*.xml"));return bean.getObject();}/*** 第一个数据源的事务* @param dataSource* @return*/@Bean(name = "db1TransactionManager")@Primarypublic DataSourceTransactionManager transactionManager(@Qualifier("db1Source") DataSource dataSource) {return new DataSourceTransactionManager(dataSource);}/*** 第一个数据源的会话模板* @param sessionFactory* @return* @throws Exception*/@Bean(name = "db1SqlSessionTemplate")@Primarypublic SqlSessionTemplate sqlSessionTemplate(@Qualifier("db1SqlSessionFactory") SqlSessionFactory sessionFactory) throws Exception {return new SqlSessionTemplate(sessionFactory);}
}
数据源2的配置:
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
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.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;import javax.sql.DataSource;/*** 数据源2配置** @Author xingo* @Date 2023/11/8*/
@Configuration
@MapperScan(basePackages = "org.example.mapper.db2", sqlSessionTemplateRef = "db2SqlSessionTemplate")
public class Db2SourceConfig {/*** 第二个数据源配置* @return*/@Bean(name="db2Source")@ConfigurationProperties(prefix = "spring.datasource.db2")public DataSource dataSource() {return DataSourceBuilder.create().build();}/*** 第二个数据源的会话工厂配置* @param dataSource* @return* @throws Exception*/@Bean(name = "db2SqlSessionFactory")public SqlSessionFactory sqlSessionFactory(@Qualifier("db2Source") DataSource dataSource) throws Exception {SqlSessionFactoryBean bean = new SqlSessionFactoryBean();bean.setDataSource(dataSource);// 指定扫描sql语句xml文件路径bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/db2/*.xml"));return bean.getObject();}/*** 第二个数据源的事务* @param dataSource* @return*/@Bean(name = "db2TransactionManager")public DataSourceTransactionManager transactionManager(@Qualifier("db2Source") DataSource dataSource) {return new DataSourceTransactionManager(dataSource);}/*** 第二个数据源的会话模板* @param sessionFactory* @return* @throws Exception*/@Bean(name = "db2SqlSessionTemplate")public SqlSessionTemplate sqlSessionTemplate(@Qualifier("db2SqlSessionFactory") SqlSessionFactory sessionFactory) throws Exception {return new SqlSessionTemplate(sessionFactory);}
}
在上面配置中分别指定了两个不同的数据源,他们用到的配置信息不同,且扫描包的路径也不同,这样就可以在代码中进行区分。
下面通过在两个不同的路径下分别创建两个映射文件方式来验证配置是否生效,在验证之前需要先准备两个数据库同时创建表并注入数据:
数据源1对应的数据:
CREATE TABLE `T_POOLPING` (`A` tinyint(1) NOT NULL,PRIMARY KEY (`A`) USING BTREE
);INSERT INTO `T_POOLPING` VALUES (1);CREATE TABLE `t_user` (`fid` int NOT NULL,`fname` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,PRIMARY KEY (`fid`) USING BTREE
) ENGINE = InnoDB;INSERT INTO `t_user` VALUES (1, '张三');
数据源2对应的数据:
CREATE TABLE `T_POOLPING` (`A` tinyint(1) NOT NULL,PRIMARY KEY (`A`) USING BTREE
);INSERT INTO `T_POOLPING` VALUES (1);CREATE TABLE `t_user` (`fid` int NOT NULL,`fname` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,PRIMARY KEY (`fid`) USING BTREE
) ENGINE = InnoDB;INSERT INTO `t_user` VALUES (1, ' 李四');
在项目的resource路径下创建两个目录:mapper/db1和mapper/db2,这两个目录用于存放xml文件,xml中就是用于编写sql语句。
mapper/db1目录下的文件内容:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.example.mapper.db1.User1Mapper"><resultMap id="userMap" type="org.example.pojo.User"><result property="id" jdbcType="INTEGER" column="fid" /><result property="name" jdbcType="VARCHAR" column="fname" /></resultMap><select id="findUserById" parameterType="hashmap" resultMap="userMap">SELECT * FROM t_user WHERE fid = #{id, jdbcType=INTEGER}</select>
</mapper>
mapper/db2目录下的文件内容:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.example.mapper.db2.User2Mapper"><resultMap id="userMap" type="org.example.pojo.User"><result property="id" jdbcType="INTEGER" column="fid" /><result property="name" jdbcType="VARCHAR" column="fname" /></resultMap><select id="findUserById" parameterType="hashmap" resultMap="userMap">SELECT * FROM t_user WHERE fid = #{id, jdbcType=INTEGER}</select>
</mapper>
这里面有一个User类:
import lombok.Data;/*** @Author xingo* @Date 2023/11/8*/
@Data
public class User {private int id;private String name;
}
再创建两个Mapper文件,对应xml文件:
import org.apache.ibatis.annotations.Mapper;
import org.example.pojo.User;
import org.springframework.stereotype.Component;/*** @Author xingo* @Date 2023/11/8*/
@Component
@Mapper
public interface User1Mapper {User findUserById(int id);
}
import org.apache.ibatis.annotations.Mapper;
import org.example.pojo.User;
import org.springframework.stereotype.Component;/*** @Author xingo* @Date 2023/11/8*/
@Component
@Mapper
public interface User2Mapper {User findUserById(int id);
}
在项目中要注意调整文件对应的包路径,避免编译问题。
创建一个controller类测试查询数据:
import org.example.mapper.db1.User1Mapper;
import org.example.mapper.db2.User2Mapper;
import org.example.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;/*** @Author xingo* @Date 2023/11/8*/
@RestController
public class DbController {@Autowiredprivate User1Mapper user1Mapper;@Autowiredprivate User2Mapper user2Mapper;@GetMapping("/get/user1")public User getuser1() {return user1Mapper.findUserById(1);}@GetMapping("/get/user2")public User getuser2() {return user2Mapper.findUserById(1);}
}
执行上面的请求会分别得到下面的内容:
请求:http://localhost:8081/get/user1
{"id": 1,"name": "张三"
}请求:http://localhost:8081/get/user2
{"id": 1,"name": " 李四"
}
可见,我们的两个数据源的配置成功了!
99%的人还看了
相似问题
- ODBC配置数据源及相关问题(“找不到工程和库”“实时错误91对象变量或with块变量未设置”等)
- .NET6使用MiniExcel根据数据源横向导出头部标题及数据
- 【Spring】使用三方包进行数据源对象(数据库)管理
- mybatis-plus3.5.3.1 支持不同数据源sql适配
- Python与ArcGIS系列(六)查找和修复数据源
- SpringBoot实现mysql与clickhouse多数据源
- SpringBoot使用MyBatis多数据源
- springboot中多数据源配置和使用
- 若依分离版——配置多数据源(mysql和oracle),实现一个方法操作多个数据源
- GNSS常用数据源汇总
猜你感兴趣
版权申明
本文"springboot中多数据源配置和使用":http://eshow365.cn/6-35336-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!
- 上一篇: 数字孪生与GIS的完美融合
- 下一篇: anker创新-2023年秋季校园招聘-音频算法方向