Spring Boot 项目中的多数据源配置

关键词:Spring Boot、多数据源配置、MySQL、SQL Server、Oracle、动态切换


✅ 摘要

在实际企业级开发中,一个 Spring Boot 项目可能需要连接多个数据库,比如 MySQL、SQL Server 和 Oracle。不同的业务模块可能依赖不同的数据源,这就要求我们掌握 如何在 Spring Boot 中灵活配置和管理多个数据源

本文将围绕以下内容进行详细讲解:

  • Spring Boot 默认数据源配置方式
  • 配置单个数据库(MySQL、SQL Server、Oracle)
  • 多数据源配置与使用(MySQL + SQL Server + Oracle)
  • 使用 AbstractRoutingDataSource 实现动态数据源切换
  • 常见问题与解决方案(驱动类、URL格式、连接失败)

每部分都配有 完整的 application.yml 配置文件和 Java 配置类代码示例


📌 一、Spring Boot 数据源配置基础

🔹 1. 默认数据源配置(以 MySQL 为例)

spring:datasource:url: jdbc:mysql://localhost:3306/test_db?useSSL=false&serverTimezone=UTCusername: rootpassword: rootdriver-class-name: com.mysql.cj.jdbc.Driver

⚠️ 注意:

  • url 要注意时区配置(serverTimezone)
  • 确保引入了正确的 JDBC 驱动包

📌 二、单个数据库的配置方式

🔹 1. MySQL 数据源配置

Maven 依赖:
<dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.33</version>
</dependency>
application.yml:
spring:datasource:mysql:url: jdbc:mysql://localhost:3306/mysql_db?useSSL=false&serverTimezone=UTCusername: rootpassword: rootdriver-class-name: com.mysql.cj.jdbc.Driver

🔹 2. SQL Server 数据源配置

Maven 依赖:
<dependency><groupId>com.microsoft.sqlserver</groupId><artifactId>mssql-jdbc</artifactId><version>12.4.0.jre8</version>
</dependency>
application.yml:
spring:datasource:sqlserver:url: jdbc:sqlserver://localhost:1433;databaseName=SqlServerDB;encrypt=true;trustServerCertificate=false;loginTimeout=30;username: sapassword: yourStrongPassworddriver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver

🔹 3. Oracle 数据源配置

Maven 依赖(需手动下载 ojdbc jar 并安装到本地仓库):
mvn install:install-file -Dfile=ojdbc8.jar -DgroupId=com.oracle.database.jdbc -DartifactId=ojdbc8 -Dversion=21.10.0.0 -Dpackaging=jar
pom.xml 添加依赖:
<dependency><groupId>com.oracle.database.jdbc</groupId><artifactId>ojdbc8</artifactId><version>21.10.0.0</version>
</dependency>
application.yml:
spring:datasource:oracle:url: jdbc:oracle:thin:@//localhost:1521/ORCLCDBusername: systempassword: oracledriver-class-name: oracle.jdbc.OracleDriver

📌 三、多数据源配置(MySQL + SQL Server + Oracle)

🔹 1. application.yml 多数据源配置

spring:datasource:mysql:url: jdbc:mysql://localhost:3306/mysql_db?useSSL=false&serverTimezone=UTCusername: rootpassword: rootdriver-class-name: com.mysql.cj.jdbc.Driversqlserver:url: jdbc:sqlserver://localhost:1433;databaseName=SqlServerDB;encrypt=true;trustServerCertificate=false;loginTimeout=30;username: sapassword: yourStrongPassworddriver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriveroracle:url: jdbc:oracle:thin:@//localhost:1521/ORCLCDBusername: systempassword: oracledriver-class-name: oracle.jdbc.OracleDriver

🔹 2. Java 配置类实现多数据源注入

第一步:定义配置属性类
@Configuration
@ConfigurationProperties(prefix = "spring.datasource")
@Data
public class DataSourceProperties {private Map<String, DataSourceConfig> datasource;@Datapublic static class DataSourceConfig {private String url;private String username;private String password;private String driverClassName;}
}

第二步:创建多个数据源 Bean
@Configuration
@RequiredArgsConstructor
public class DataSourceConfig {private final DataSourceProperties dataSourceProperties;@Bean("mysqlDataSource")@ConfigurationProperties(prefix = "spring.datasource.mysql")public DataSource mysqlDataSource() {return DataSourceBuilder.create().url(dataSourceProperties.getDatasource().get("mysql").getUrl()).username(dataSourceProperties.getDatasource().get("mysql").getUsername()).password(dataSourceProperties.getDatasource().get("mysql").getPassword()).driverClassName(dataSourceProperties.getDatasource().get("mysql").getDriverClassName()).build();}@Bean("sqlServerDataSource")public DataSource sqlServerDataSource() {return DataSourceBuilder.create().url(dataSourceProperties.getDatasource().get("sqlserver").getUrl()).username(dataSourceProperties.getDatasource().get("sqlserver").getUsername()).password(dataSourceProperties.getDatasource().get("sqlserver").getPassword()).driverClassName(dataSourceProperties.getDatasource().get("sqlserver").getDriverClassName()).build();}@Bean("oracleDataSource")public DataSource oracleDataSource() {return DataSourceBuilder.create().url(dataSourceProperties.getDatasource().get("oracle").getUrl()).username(dataSourceProperties.getDatasource().get("oracle").getUsername()).password(dataSourceProperties.getDatasource().get("oracle").getPassword()).driverClassName(dataSourceProperties.getDatasource().get("oracle").getDriverClassName()).build();}
}

📌 四、动态切换数据源(基于 AbstractRoutingDataSource)

🔹 1. 定义当前线程使用的数据源标识

public class DynamicDataSourceContextHolder {private static final ThreadLocal<String> CONTEXT_HOLDER = new ThreadLocal<>();public static void setDataSourceKey(String key) {CONTEXT_HOLDER.set(key);}public static String getDataSourceKey() {return CONTEXT_HOLDER.get();}public static void clearDataSourceKey() {CONTEXT_HOLDER.remove();}
}

🔹 2. 自定义 AbstractRoutingDataSource

@Component
@RequiredArgsConstructor
public class DynamicDataSource extends AbstractRoutingDataSource {private final DataSource mysqlDataSource;private final DataSource sqlServerDataSource;private final DataSource oracleDataSource;@PostConstructpublic void init() {Map<Object, Object> targetDataSources = new HashMap<>();targetDataSources.put("mysql", mysqlDataSource);targetDataSources.put("sqlserver", sqlServerDataSource);targetDataSources.put("oracle", oracleDataSource);this.setTargetDataSources(targetDataSources);this.setDefaultTargetDataSource(mysqlDataSource); // 设置默认数据源this.afterPropertiesSet();}@Overrideprotected Object determineCurrentLookupKey() {return DynamicDataSourceContextHolder.getDataSourceKey();}
}

🔹 3. 配置为事务管理器的数据源

@Bean
public PlatformTransactionManager transactionManager(DynamicDataSource dynamicDataSource) {return new DataSourceTransactionManager(dynamicDataSource);
}

🔹 4. 在 Service 层使用动态数据源

@Service
@RequiredArgsConstructor
public class UserService {private final JdbcTemplate jdbcTemplate;public void queryFromMysql() {DynamicDataSourceContextHolder.setDataSourceKey("mysql");List<Map<String, Object>> result = jdbcTemplate.queryForList("SELECT * FROM user");System.out.println("MySQL 查询结果:" + result);}public void queryFromSqlServer() {DynamicDataSourceContextHolder.setDataSourceKey("sqlserver");List<Map<String, Object>> result = jdbcTemplate.queryForList("SELECT * FROM Users");System.out.println("SQL Server 查询结果:" + result);}public void queryFromOracle() {DynamicDataSourceContextHolder.setDataSourceKey("oracle");List<Map<String, Object>> result = jdbcTemplate.queryForList("SELECT * FROM employees");System.out.println("Oracle 查询结果:" + result);}
}

✅ 总结

以下几点为本文重点:

模块技能点
单数据源配置MySQL、SQL Server、Oracle 的基本配置方法
多数据源配置如何在一个 Spring Boot 项目中配置多个数据源
动态数据源切换使用 AbstractRoutingDataSource 实现运行时切换
实战能力结合 JdbcTemplate、事务管理器使用多数据源

这些技能是你构建复杂微服务系统、支持多数据库架构的重要基础。


📚 参考资料

  • Spring Boot 官方文档
  • Spring Data Access 文档

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.pswp.cn/news/913757.shtml
繁体地址,请注明出处:http://hk.pswp.cn/news/913757.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

MATLAB/Simulink电机控制仿真代做 同步异步永磁直驱磁阻双馈无刷

以下是针对 MATLAB/Simulink 电机控制仿真 的系统性解决方案&#xff0c;涵盖 同步电机、异步电机、永磁电机、直驱电机、磁阻电机、双馈电机、无刷直流电机&#xff08;BLDC&#xff09; 的建模与控制策略实现&#xff0c;支持代做服务的技术细节和代码示例。一、电机建模与仿…

限流算法深度探索:从理论到实践的生产级避坑指南

凌晨3点&#xff0c;监控警报刺耳地尖叫着。我盯着屏幕上垂直下跌的服务可用性曲线&#xff0c;意识到那个被忽视的限流配置项终于引爆了——每秒1000次的支付请求正像洪水般冲垮我们的系统。这次事故让我深刻理解&#xff1a;限流不是可选项&#xff0c;而是分布式系统的生存法…

企业级后台管理系统的困境与飞算 JavaAI 的破局之道

企业级后台管理系统如 CRM&#xff08;客户关系管理系统&#xff09;、ERP&#xff08;企业资源计划系统&#xff09;已成为支撑企业高效运转的核心骨架。它们如同企业的 “神经中枢”&#xff0c;串联起客户数据、财务信息、供应链流程等关键环节&#xff0c;为决策制定、业务…

快速上手百宝箱搭建知识闯关游戏助手

引言&#xff1a;让学习更有趣&#xff0c;AI 赋能知识闯关新体验 1.在信息爆炸的时代&#xff0c;传统的填鸭式教学方式已难以满足现代用户对高效、个性化和趣味化学习的需求。越来越多的学习者倾向于通过互动性强、参与感十足的方式获取知识。在此背景下&#xff0c;游戏化学…

【YOLOv11-目标检测】目标检测数据格式(官方说明)

原文链接&#xff1a; https://docs.ultralytics.com/datasets/detect/ 写在前面 训练一个鲁棒且准确的目标检测模型需要一个全面的数据集。本文介绍&#xff1a;与Ultralytics YOLO模型兼容的各种数据集格式&#xff0c;并深入解析了它们的结构、使用方法以及如何在不同的格…

yolo8实现目标检测

✅步骤一&#xff1a;安装 PyTorch&#xff08;M1 专用&#xff09;# 推荐使用官方 MPS 后端&#xff08;Apple Metal 加速&#xff09; pip install torch torchvision torchaudio确认是否使用了 Apple MPS&#xff1a;import torch print(torch.backends.mps.is_available()…

安全管理协议(SMP):配对流程、密钥生成与防中间人攻击——蓝牙面试核心考点精解

一、SMP 核心知识点高频考点解析1.1 SMP 在蓝牙安全体系中的定位考点&#xff1a;SMP 的功能与协议栈位置解析&#xff1a; SMP&#xff08;Security Manager Protocol&#xff0c;安全管理协议&#xff09;是蓝牙核心规范中负责设备配对、密钥生成与安全连接的关键协议&#x…

U盘实现——U 盘类特殊命令

文章目录 U 盘类特殊命令U 盘的命令封包命令阶段数据阶段状态阶段get max luninquiry(0x12)read format capacities(0x23)read capacity(0x25)mode sense(0x1a)test unit ready(0x00)read(10) 0x28write(10) 0x2aU 盘类特殊命令 U 盘的命令封包 命令阶段 命令阶段主要由主机通…

深度帖:浏览器的事件循环与JS异步

一、浏览器进程 早期的浏览器是单进程的&#xff0c;所有功能杂糅在一个进程中&#xff1b;现在的浏览器是多进程的&#xff0c;包含浏览器进程、网络进程、渲染进程等等&#xff0c;每个进程负责的工作不同。浏览器进程&#xff1a;负责界面显示&#xff08;地址栏、书签、历史…

Linux网络:UDP socket创建流程与简单通信

本文介绍 UDP 服务端与客户端 的创建流程&#xff0c;和相关的函数接口 核心流程 创建 socket → socket()填写服务器地址信息 → sockaddr_in 结构体绑定地址和端口 → bind()接收并响应客户端数据 → recvfrom() / sendto()socket() #include<sys/so…

windows内核研究(系统调用 1)

WindowsAPI函数的调用过程什么是WindowsApi&#xff1f;Windows API&#xff08;Application Programming Interface&#xff0c;应用程序编程接口&#xff09;是微软为Windows操作系统提供的一套系统级编程接口&#xff0c;允许开发者与操作系统内核、硬件、系统服务等进行交互…

【前端】异步任务风控验证与轮询机制技术方案(通用笔记版)

一、背景场景 在某类生成任务中&#xff0c;例如用户点击“执行任务”按钮后触发一个较耗时的后端操作&#xff08;如生成报告、渲染图像、转码视频等&#xff09;&#xff0c;由于其调用了模型、渲染服务或需要较长处理时间&#xff0c;为了防止接口被频繁恶意调用&#xff0c…

Vim 编辑器常用操作详解(新手快速上手指南)

&#x1f4bb; Vim 编辑器常用操作详解&#xff08;新手快速上手指南&#xff09;作者&#xff1a;Lixin 日期&#xff1a;2025-07-09 学习内容&#xff1a;Vim 编辑器基础 常用快捷键 Xshell/Xftp连接 Linux基本操作 学习目标&#xff1a;掌握 Vim 的三种常用模式切换与基本…

OpenGL 生成深度图与点云

文章目录 一、简介二、实现代码三、实现效果一、简介 这里基于OpenGL实现对一个Mesh对象深度图的获取,思路其实很简单,直接通过glReadPixels函数获取整个OpenGL中的深度缓冲数据即可;那么反过来我们如果有了这个深度图之后,也可以基于每个像素点的深度值,反算出图像中的深…

25春云曦期末考复现

Web 疯狂星期四 <?php$tg1u$_GET[tg1u];if(!preg_match("/0|1|[3-9]|\~|\|\|\#|\\$|\%|\^|\&|\*|\&#xff08;|\&#xff09;|\-|\|\|\{|\[|\]|\}|\:|\|\"|\,|\<|\.|\>|\/|\?|\\\\|localeconv|pos|current|print|var|dump|getallheaders|get|define…

从Prompt到预训练:掌握大模型核心技术的阶梯式进化

本文较长&#xff0c;建议点赞收藏&#xff0c;以免遗失。更多AI大模型应用开发学习视频及资料&#xff0c;尽在聚客AI学院。 在探讨大模型&#xff08;LLM&#xff09;的四阶段技术时&#xff0c;我们可以从Prompt Engineering&#xff08;提示工程&#xff09;、AI Agent&…

手机文件夹隐藏工具,一键保护隐私

软件介绍 今天为大家推荐一款手机文件夹隐藏工具——Amarok&#xff0c;它能帮助用户快速隐藏手机中的私密文件夹&#xff0c;保护个人隐私。 核心功能 Amarok主打文件夹隐藏功能&#xff0c;操作简单便捷。需要注意的是&#xff0c;虽然软件支持应用隐藏功能&#xff0…

day10-Redis面试篇

经过前几天的学习&#xff0c;大家已经掌握了微服务相关技术的实际应用&#xff0c;能够应对企业开发的要求了。不过大家都知道在IT领域往往都是面试造火箭&#xff0c;实际工作拧螺丝。为了更好的应对面试&#xff0c;让大家能拿到更高的offer&#xff0c;我们接下来就讲讲“造…

Axure版本Element组件库-免费版

Axure版本的Element组件库基于Element UI/Plus设计规范开发&#xff0c;涵盖了从基础元素到复杂交互的全品类组件&#xff0c;能高效支撑各类Web原型设计&#xff0c;尤其适合后台管理系统、企业级应用等场景。以下从核心类别展开详细介绍&#xff1a; 链接地址 添加图片注释&a…

记一次JVM问题排查

今天遇到了1次OOM&#xff0c;导入万条数据的Excel于是让运维进行排查。正式环境显示内存还有很多 于是我说让运维加上参数 -XX:HeapDumpOnOutOfMemoryError&#xff0c;出现OOM的时候dump到文件中&#xff0c;将堆内存设置为4G&#xff0c;在Idea上进行测试于是让运维在生产环…