国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

springboot dynamic-datasource 實現(xiàn)動態(tài)切換數(shù)據(jù)源-多租戶-配置文件切換-基于dynamic-datasource

這篇具有很好參考價值的文章主要介紹了springboot dynamic-datasource 實現(xiàn)動態(tài)切換數(shù)據(jù)源-多租戶-配置文件切換-基于dynamic-datasource。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。

1、目標(biāo)

1、實現(xiàn)動態(tài)切換數(shù)據(jù)源
2、實現(xiàn)配置多數(shù)據(jù)源
3、實現(xiàn)讀寫分離也可以用多數(shù)據(jù)源方式
4、選擇
dynamic-datasource集成了很多ORM的框架,其中,使用比較多的是druid,但有一些東西開始收費了
druid也可以自行配置,配置多了點

目前版本只支持單一位置加載數(shù)據(jù)源(只能從配置文件或者自定義加載數(shù)據(jù)源),不能多位置加載數(shù)據(jù)源
目前版本未實現(xiàn)動態(tài)添加數(shù)據(jù)源(在切換數(shù)據(jù)源時,不存在的數(shù)據(jù)源在數(shù)據(jù)庫查詢,添加進(jìn)數(shù)據(jù)源連接池)

2、源代碼

springboot版本:2.3.1.RELEASE
dynamic-datasource版本:3.5.1
官方文檔:https://www.kancloud.cn/tracy5546/dynamic-datasource/2264611
實現(xiàn)源代碼地址

3、實現(xiàn)

pom.xml配置

	<dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>dynamic-datasource-spring-boot-starter</artifactId>
        <version>3.5.1</version>
    </dependency>

application.yml配置


spring:
  application:
    name: microservice-boot-common
  # Jackson 配置項
  jackson:
    #    serialization:
    #      write-dates-as-timestamps: true # 設(shè)置 Date 的格式,使用時間戳
    #      write-date-timestamps-as-nanoseconds: false # 設(shè)置不使用 nanoseconds 的格式。例如說 1611460870.401,而是直接 1611460870401
    #      write-durations-as-timestamps: true # 設(shè)置 Duration 的格式,使用時間戳
    #      fail-on-empty-beans: false # 允許序列化無屬性的 Bean
    date-format: yyyy-MM-dd HH:mm:ss
    time-zone: GMT+8

  datasource:
    dynamic:
      primary: master #設(shè)置默認(rèn)的數(shù)據(jù)源或者數(shù)據(jù)源組,默認(rèn)值即為master
      strict: false #嚴(yán)格匹配數(shù)據(jù)源,默認(rèn)false. true未匹配到指定數(shù)據(jù)源時拋異常,false使用默認(rèn)數(shù)據(jù)源
      datasource:
        druid: # Druid 【監(jiān)控】相關(guān)的全局配置
          web-stat-filter:
            enabled: true
          stat-view-servlet:
            enabled: true
            allow: # 設(shè)置白名單,不填則允許所有訪問
            url-pattern: /druid/*
            login-username: test
            login-password: test
          filter:
            stat:
              enabled: true
              log-slow-sql: true # 慢 SQL 記錄
              slow-sql-millis: 1000
              merge-sql: true
            wall:
              config:
                multi-statement-allow: true
          initial-size: 4 # 初始連接數(shù)
          min-idle: 4 # 最小連接池數(shù)量
          max-active: 50 # 最大連接池數(shù)量
          max-wait: 600000 # 配置獲取連接等待超時的時間,單位:毫秒
          time-between-eviction-runs-millis: 60000 # 配置間隔多久才進(jìn)行一次檢測,檢測需要關(guān)閉的空閑連接,單位:毫秒
          min-evictable-idle-time-millis: 300000 # 配置一個連接在池中最小生存的時間,單位:毫秒
          max-evictable-idle-time-millis: 900000 # 配置一個連接在池中最大生存的時間,單位:毫秒
          validation-query: SELECT 1 # 配置檢測連接是否有效
          test-while-idle: true
          test-on-borrow: false
          test-on-return: false
          name: master
        master:
          driver-class-name: com.mysql.jdbc.Driver # 3.2.0開始支持SPI可省略此配置
          url: jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&allowPublicKeyRetrieval=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8&allowMultiQueries=true&nullCatalogMeansCurrent=true
          username: root
          password: 123456
        slave_1:
          driver-class-name: com.mysql.jdbc.Driver
          url: jdbc:mysql://127.0.0.1:3306/test2?useUnicode=true&allowPublicKeyRetrieval=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8&allowMultiQueries=true&nullCatalogMeansCurrent=true
          username: root
          password: 123456




# MyBatis Plus 的配置項
mybatis-plus:
  configuration:
    map-underscore-to-camel-case: true # 雖然默認(rèn)為 true ,但是還是顯示去指定下。
  global-config:
    db-config:
      #      id-type: NONE # “智能”模式,基于 IdTypeEnvironmentPostProcessor + 數(shù)據(jù)源的類型,自動適配成 AUTO、INPUT 模式。
      id-type: AUTO # 自增 ID,適合 MySQL 等直接自增的數(shù)據(jù)庫
      #      id-type: INPUT # 用戶輸入 ID,適合 Oracle、PostgreSQL、Kingbase、DB2、H2 數(shù)據(jù)庫
      #      id-type: ASSIGN_ID # 分配 ID,默認(rèn)使用雪花算法。注意,Oracle、PostgreSQL、Kingbase、DB2、H2 數(shù)據(jù)庫時,需要去除實體類上的 @KeySequence 注解
      logic-delete-value: 1 # 邏輯已刪除值(默認(rèn)為 1)
      logic-not-delete-value: 0 # 邏輯未刪除值(默認(rèn)為 0)
      logic-delete-field: deleted_tag
      table-prefix: t_
    banner: false
  type-aliases-package: org.lwd.microservice.boot.common.dao
  mapper-locations: classpath*:/mapper/**/*.xml

手動切換

    @DS("slave_1")
     @Override
    public BaseResult<TenantDataSourceDTO> getTenantDataSourceByPk(String pk) {
        BaseResult<TenantDataSourceDTO> baseResult = BaseResult.success();
        TenantDataSource domain = this.getById(pk);
        baseResult.setData(TenantDataSourceConvertor.INSTANCE.toDTO(domain));
        return baseResult;
     }

動態(tài)切換-aop模式

package org.lwd.microservice.boot.common.aop;

import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;

/**
 * 數(shù)據(jù)源攔截-aop模式
 *
 * @author weidong
 * @version V1.0.0
 * @since 2023/6/13
 */
@Order(1)
@Aspect
@EnableAspectJAutoProxy(proxyTargetClass = true)
@Component
@Slf4j
public class DataSourceChangeAdvisor {
    /**
     * 按需設(shè)置需要切換的模式
     */
    @Pointcut("@within(org.springframework.web.bind.annotation.RestController)")
    public void pointDataSource() {
    }

    /**
     * 需要定義模塊的規(guī)則
     * @param joinPoint
     * @return
     * @throws Throwable
     */
    @Around("pointDataSource()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        try {
            //獲取當(dāng)前請求對象
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (attributes != null) {
                HttpServletRequest request = attributes.getRequest();
                String uri = request.getRequestURI();
                //String url = request.getRequestURL().toString();
                String[] uriArr = uri.split("/");
                if (uriArr[uriArr.length - 1].equals("detail")) {
                    log.info("datasource1------");
                    DynamicDataSourceContextHolder.push("master");
                } else {
                    log.info("datasource2------");
                    DynamicDataSourceContextHolder.push("slave_1");
                } 
            }
        } catch (Exception e) {
            log.error("日志攔截異常", e);
        } finally {
            return joinPoint.proceed();
        }
    }
}


動態(tài)切換-攔截器模式

package org.lwd.microservice.boot.common.interceptor;

import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 動態(tài)數(shù)據(jù)源-攔截器模式-需要自定義規(guī)則
 * @author weidong
 * @version V1.0.0
 * @since 2023/6/16
 */
@Slf4j
public class DynamicDataSourceChangeInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
        //String url = request.getRequestURL().toString();
        String[] uriArr = uri.split("/");
        if (uriArr[uriArr.length - 1].equals("detail")) {
            log.info("interceptor datasource1------");
            DynamicDataSourceContextHolder.push("master");
        } else {
            log.info("interceptor datasource2------");
            DynamicDataSourceContextHolder.push("slave_1");
        } 
        return true;
    }
}

package org.lwd.microservice.boot.common.interceptor;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * mvc攔截器-自定義攔截路徑
 * @author weidong
 * @version V1.0.0
 * @since 2023/6/16
 */
@Configuration
public class DynamicDataSourceChangeInterceptorConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //如果攔截全部可以設(shè)置為 /**
        String [] path = {"/tenantDataSource/**"};
        //不需要攔截的接口路徑
        String [] excludePath = {};
        DynamicDataSourceChangeInterceptor dynamicDataSourceChangeInterceptor = new DynamicDataSourceChangeInterceptor();
        registry.addInterceptor(dynamicDataSourceChangeInterceptor).addPathPatterns(path).excludePathPatterns(excludePath);
    }
}

4、總結(jié)

這種方式是配置文件的方式,可對立的配置文件配置多個數(shù)據(jù)源,
但是動態(tài)增加或者減少數(shù)據(jù)源,需要自己實現(xiàn)一部分代碼,看下一篇文章文章來源地址http://www.zghlxwxcb.cn/news/detail-487419.html

外傳

?? 原創(chuàng)不易,如若本文能夠幫助到您的同學(xué)
?? 支持我:關(guān)注我+點贊??+收藏??
?? 留言:探討問題,看到立馬回復(fù)
?? 格言:己所不欲勿施于人 揚帆起航、游歷人生、永不言棄!??

到了這里,關(guān)于springboot dynamic-datasource 實現(xiàn)動態(tài)切換數(shù)據(jù)源-多租戶-配置文件切換-基于dynamic-datasource的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實不符,請點擊違法舉報進(jìn)行投訴反饋,一經(jīng)查實,立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費用

相關(guān)文章

  • shardingsphere5.x整合springboot+dynamic-datasource多數(shù)據(jù)源實戰(zhàn)

    本文是在springboot整合分庫分表的基礎(chǔ)上添加了多數(shù)據(jù)源,建議先看上一篇shardingsphere5.x整合springboot分庫分表實戰(zhàn)_任人人人呢的博客-CSDN博客 pom.xml配置: yml配置: 添加多數(shù)據(jù)源配置類: 添加多數(shù)據(jù)源常量類: Mapper文件

    2024年02月13日
    瀏覽(23)
  • Springboot+mybatis-plus+dynamic-datasource+Druid 多數(shù)據(jù)源 分布式事務(wù)

    Springboot+mybatis-plus+dynamic-datasource+Druid 多數(shù)據(jù)源 分布式事務(wù)

    背景 處理多數(shù)據(jù)源事務(wù)一直是一個復(fù)雜而棘手的問題,通常我們有兩種主流的解決方法。 第一種是通過Atomikos手動創(chuàng)建多數(shù)據(jù)源事務(wù),這種方法更適合數(shù)據(jù)源數(shù)量較少,參數(shù)配置不復(fù)雜,對性能要求不高的項目。然而,這種方法的最大困難在于需要手動配置大量設(shè)置,這可能

    2024年02月11日
    瀏覽(26)
  • dynamic-datasource can not find primary datasource

    dynamic-datasource can not find primary datasource

    動態(tài)數(shù)據(jù)源找不到主數(shù)據(jù)源 可能導(dǎo)入多數(shù)據(jù)源依賴導(dǎo)致 把依賴注釋 運行成功

    2024年02月08日
    瀏覽(19)
  • 【源碼解析】多數(shù)據(jù)源 dynamic-datasource快速入門及源碼解析

    【源碼解析】多數(shù)據(jù)源 dynamic-datasource快速入門及源碼解析

    啟動的時候,會加載在 dynamic-datasource-spring-boot-starter 的jar包中的 spring.factories 在 DynamicDataSourceAutoConfiguration 會注入 DynamicRoutingDataSource DynamicRoutingDataSource#afterPropertiesSet ,系統(tǒng)啟動的時候會加載所有的數(shù)據(jù)源 在 DynamicDataSourceAutoConfiguration 會注入 DynamicDataSourceProvider AbstractData

    2023年04月21日
    瀏覽(21)
  • dynamic-datasource Please check the setting of primary解決方案

    dynamic-datasource Please check the setting of primary解決方案

    報這個錯的原因是數(shù)據(jù)庫使用多數(shù)據(jù)源沒有指定主數(shù)據(jù)源導(dǎo)致的錯誤。 ?解決方法如圖所示,通過配置指定dynamic的primary指定主數(shù)據(jù)庫的配置 切記箭頭兩處的名稱一樣

    2024年02月13日
    瀏覽(33)
  • spring boot mybatis-plus dynamic-datasource 配置文件 相關(guān)依賴環(huán)境配置

    spring boot mybatis-plus dynamic-datasource 配置文件 相關(guān)依賴環(huán)境配置

    spring boot mybatis-plus dynamic-datasource 配置文件 相關(guān)依賴環(huán)境配置 ##yaml配置 ##父級pom.xml配置 ##子模塊pom.xml配置 ##表結(jié)構(gòu) ##Test.java ##TestMapper.xml ##TestMapper.java ##TestService.java ##TestController ##項目啟動類BootStrap.java ##瀏覽器訪問 192.168.3.188:8866/yym/test/v1/test

    2024年02月02日
    瀏覽(32)
  • 使用mybatis和dynamic-datasource-spring-boot-starter動態(tài)切換數(shù)據(jù)源操作數(shù)據(jù)庫

    記錄 :415 場景 :使用mybatis和dynamic-datasource-spring-boot-starter動態(tài)切換數(shù)據(jù)源操作數(shù)據(jù)庫。 版本 :JDK 1.8,Spring?Boot 2.6.3,dynamic-datasource-spring-boot-starter-3.3.2,mybatis-3.5.9。 源碼 :https://github.com/baomidou/dynamic-datasource-spring-boot-starter dynamic-datasource-spring-boot-starter :一個基于springboot的快

    2023年04月19日
    瀏覽(23)
  • 使用dynamic-datasource-spring-boot-starter動態(tài)切換數(shù)據(jù)源操作數(shù)據(jù)庫(MyBatis-3.5.9)

    記錄 :383 場景 :使用dynamic-datasource-spring-boot-starter動態(tài)切換數(shù)據(jù)源,使用MyBatis操作數(shù)據(jù)庫。提供三種示例:一,使用@DS注解作用到類上。二,使用@DS注解作用到方法上。三,不使用注解,使用DynamicDataSourceContextHolder類在方法內(nèi)靈活切換不同數(shù)據(jù)源。 源碼: https://github.com/

    2024年01月20日
    瀏覽(25)
  • MyBatis Plus 插件 動態(tài)數(shù)據(jù)源實現(xiàn)原理與源碼講解 (dynamic-datasource-spring-boot-starter-master)

    MyBatis Plus 插件 動態(tài)數(shù)據(jù)源實現(xiàn)原理與源碼講解 (dynamic-datasource-spring-boot-starter-master)

    目錄 1. 介紹 2. 基本原理 3. 源碼介紹 3.1 使用 AOP 攔截,方法執(zhí)行前獲取到當(dāng)前方法要用的數(shù)據(jù)源 3.2 實現(xiàn)自定義?DataSource 接口,實現(xiàn) DataSource 接口的 getConnect 方法做動態(tài)處理 多數(shù)據(jù)源即一個項目中同時存在多個不同的數(shù)據(jù)庫連接池。 比如 127.0.0.1:3306/test? ?127.0.0.1:3307/test?

    2024年02月07日
    瀏覽(28)
  • Dynamic DataSource 多數(shù)據(jù)源配置【 Springboot + DataSource + MyBatis Plus + Druid】

    Dynamic DataSource 多數(shù)據(jù)源配置【 Springboot + DataSource + MyBatis Plus + Druid】

    MybatisPlus多數(shù)據(jù)源配置主要解決的是多數(shù)據(jù)庫連接和切換的問題。在一些大型應(yīng)用中,由于數(shù)據(jù)量的增長或者業(yè)務(wù)模塊的增多,可能需要訪問多個數(shù)據(jù)庫。這時,就需要配置多個數(shù)據(jù)源。 2.1.1、引用依賴 2.1.2、application.yml 配置 2.1.3、通用配置類 2.1.4、使用方式 這里便不過多的

    2024年02月03日
    瀏覽(32)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包