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
英文地址,請注明出處:http://en.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上進行測試于是讓運維在生產環…