springboot —— 多數據源

来源:https://www.cnblogs.com/gdwkong/archive/2018/09/19/9678179.html
-Advertisement-
Play Games

本文主要介紹如何在一個springboot項目配置兩個數據源(mysql和oracle)。 ...


本文主要介紹如何在一個springboot項目配置兩個數據源(mysql和oracle);

1、引進相關依賴

<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>
<!--oracle 驅動 -->
<dependency>
    <groupId>com.oracle</groupId>
    <artifactId>ojdbc6</artifactId>
    <version>11.1.0.7.0</version>
</dependency>

當ojdbc驅動包版本過低,會報如下圖所示錯誤,即驅動jar與資料庫版本不相容:

2、於applicationContext.yml中配置數據源連接參數:

 1     Spring:
 2         datasource:
 3             base:
 4                  driver-class-name: com.mysql.jdbc.Driver
 5                  jdbc-url: ${base.db.url}
 6                  username: ${base.db.username}
 7                  password: ${base.db.password}
 8             oa:
 9                  driver-class-name: oracle.jdbc.driver.OracleDriver
10                  jdbc-url: ${oa.db.urL}
11                  username: ${oa.db.username}
12                  password: ${oa.db.password}
13             hikari:
14                  max-lifetime: 60000
15                  login-timeout: 5
16                  validation-timeout: 3000
17                  connection-timeout: 60000
18                  idle-timeout: 60000

3、多數據源配置文件,讀取對應連接參數

Package com.**.config;

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 javax.sql.DataSource;

public class MultiDataSourceConfig {

    @Bean (name = "primaryDataSource")
    @Qualifier("primaryDataSource")
    @Primary //定義主數據源
    @ConfigurationProperties (prefix = "spring.datasource.Base")
    public DataSource primaryDataSource () { return DataSourceBuilder.create().build (); }

    @Bean (name = "secondaryDataSource")
    @Qualifier ("secondaryDataSource")
    @ConfigurationProperties (prefix = "spring.datasource.oa")
    public DataSource secondaryDataSource () { return DataSourceBuilder.create().build (); }

}

3、主數據源配置,指定掃描對應mapper文件以及對應xml文件,在使用mapper包下的mapper文件時會自動使用對應sql會話

Package com.**.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.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframeworkcore.io.support.PathMatchingResourcePatternResolver;
import org.spr ingframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import javax.sql.DataSource;

@Configuration
@MapperScan (basePackages = "com.**.mapper", sqlSessionTemplateRef = "primarySqlSessionTemplate")
public class SqlSessionTemplate1 {

    @Bean (name = "primarySqlSessionFactory")
    @Primary
    public SqlSessionFactory primarySqlSessionFactory  (@Qualifier("primaryDataSource") DataSource dataSource)
            throws Exception{
        SqLSessionFactoryBean bean = new SqlSessionFactoryBean ();
        bean.setDataSource (dataSource);
        bean.setMapperLocations (new PathMatchingResourcePatternResolver().getResources (locationPattern: "classpath: mybatis/mapper/*. XmL"));
        return bean.getObject();
    }

    /**
     * 配置聲明式事務管理器
     */
    @Bean (name = "primaryTransactionManager")
    @Primary
    public PlatformTransactionManager primaryTransactionManager  (@Qualifier("primaryDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager  (dataSource);
    }

    @Bean (name = "primarySqlSessionTemplate")
    @Primary
    public SqlSessionTemplatel primarySqlSessionTemplate(@Qualifier("primarySqlSesionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplatel(sqlSessionFactory);
    }
}

4、第二數據源配置,指定掃描對應mapper文件以及對應xml文件,在使用mapper包下的mapper文件時會自動使用對應sql會話

Package com.**.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.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.secondary;
import org.springframeworkcore.io.support.PathMatchingResourcePatternResolver;
import org.spr ingframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import javax.sql.DataSource;

@Configuration
@MapperScan (basePackages = "com.**.oraclemapper", sqlSessionTemplateRef = "secondarySqlSessionTemplate")
public class SqlSessionTemplate2 {

    @Bean (name = "secondarySqlSessionFactory")
    public SqlSessionFactory secondarySqlSessionFactory  (@Qualifier("secondaryDataSource") DataSource dataSource)
            throws Exception{
        SqLSessionFactoryBean bean = new SqlSessionFactoryBean ();
        bean.setDataSource (dataSource);
        bean.setMapperLocations (new PathMatchingResourcePatternResolver().getResources (locationPattern: "classpath: mybatis/oraclemapper/*. XmL"));
        return bean.getObject();
    }

    /**
     * 配置聲明式事務管理器
     */
    @Bean (name = "secondaryTransactionManager")
    public PlatformTransactionManager secondaryTransactionManager  (@Qualifier("secondaryDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager  (dataSource);
    }

    @Bean (name = "secondarySqlSessionTemplate")
    public SqlSessionTemplatel secondarySqlSessionTemplate(@Qualifier("secondarySqlSesionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplatel(sqlSessionFactory);
    }
}

至此,在service層可以像單數據源一樣使用了。


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 說起js,對很多初學者來說可能還是比較費力的,本人也是覺得js功底還是不夠扎實,所以把有些東西在學習一遍,順便分享出來希望可以幫到有需要的人 “三元運算符” 什麼是三元運算符 條件?條件成立執行:條件不成立執行; 相當於簡單的if()else()語句 舉個慄子: var num=10; if(num ...
  • 什麼是快速開發框架 前言 做為一個程式員,在開發的過程中會發現,有框架同無框架,做起事來是完全不同的概念,關係到開發的效率、程式的健壯、性能、團隊協作、後續功能維護、擴展......等方方面面的事情。很多朋友在學習搭建自己的框架,很多公司也在創建或使用自己的框架,網上開源的框架多如牛毛,每年新上線的 ...
  • 前言:王福朋老師的 "JavaScript原型和閉包系列" 文章看了不下三遍了,最為一個初學者,每次看的時候都會有一種 “大徹大悟” 的感覺,而看完之後卻總是一臉懵逼。 原型與閉包 可以說是 JavaScirpt 中理解起來最難的部分了,當然,我也只是瞭解到了一些皮毛,對於 JavaScript O ...
  • 標準庫 bind 函數 詳解 bind函數:接收一個函數名作為參數,生成一個新的函數。 arg_list中的參數可能包含入_1, _2等,這些是新函數newCallable的參數。 在這篇博客 "lambda 表達式 介紹" 中,討論了find_if的第三個參數的問題,當時是用lambda表達式解決 ...
  • 一、為什麼要Maven 在開發中經常需要依賴第三方的包,包與包之間存在依賴關係,版本間還有相容性問題,有時還里要將舊的包升級或降級,當項目複雜到一定程度時包管理變得非常重要。 Maven是當前最受歡迎的Java項目管理構建自動化綜合工具,類似以前Java中的Ant、node.js中的npm、dotN ...
  • Java當中的常量池 在 虛擬機 中,記憶體分佈為: 虛擬機堆,程式計數器,本地方法棧,虛擬機棧,方法區。 程式計數器是 執行程式的流水線,是用來存放一些指令的,本地方法棧是 操作系統方法所使用的棧,而虛擬機棧是用來執行程式代碼的棧,在方法區中有 類變數,類信息,方法信息,常量池(符號的引用,以表的形 ...
  • Python基礎:print & input & 變數 & 運算符 & Python數據類型 & 運算符與表達式 Python 基礎 1 註釋 單行註釋 多行註釋 三個單引號'''括起來 三個雙引號"""括起來 print 輸出 作用:列印到屏幕上一些信息 可以接受多個字元串,用逗號分隔,遇到逗號會 ...
  • 本文主要記錄springboot中配置RestTemplate。 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...