最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

SpringBoot 如何實現(xiàn)多版本接口的方法步驟

 更新時間:2026年04月14日 09:51:37   作者:(farerboy)  
本文主要介紹了SpringBoot 如何實現(xiàn)多版本接口的方法步驟,包括幾種接口多版本控制的方式,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

前言

為什么接口會出現(xiàn)多個版本?

一般來說,Restful API 接口是提供給其它模塊,系統(tǒng)或是其他公司使用,不能隨意頻繁的變更。然而,需求和業(yè)務(wù)不斷變化,接口和參數(shù)也會發(fā)生相應(yīng)的變化。如果直接對原來的接口進(jìn)行修改,勢必會影響線其他系統(tǒng)的正常運行。這就必須對 api 接口進(jìn)行有效的版本控制。

接口多版本的方式

相同URL,用不同的版本參數(shù)區(qū)分

  1. api.test.com/user?version=v1
  2. api.test.com/user?version=v2
  • version=v1 表示 v1版本的接口, 保持原有接口不動
  • version=v2 表示 v2版本的接口,更新新的接口

區(qū)分不同的接口域名

不同的版本有不同的子域名, 路由到不同的實例:

  1. v1.api.test.com/user
  2. v2.api.test.com/user
  • v1版本的接口, 保持原有接口不動, 路由到instance1
  • v2版本的接口,更新新的接口, 路由到instance2

網(wǎng)關(guān)路由不同子目錄到不同的實例

  1. api.test.com/v1/user
  2. api.test.com/v2/user
  • v1版本的接口, 保持原有接口不動, 路由到instance1
  • v2版本的接口,更新新的接口, 路由到instance2

同一實例,用注解隔離不同版本控制

  1. api.test.com/v1/user
  2. api.test.com/v2/user
  • v1版本的接口, 保持原有接口不動,匹配@ApiVersion(“1”)的handlerMapping
  • v2版本的接口,更新新的接口,匹配@ApiVersion(“2”)的handlerMapping

下面咱們主要展示第四種單一實例中如何優(yōu)雅的控制接口的版本。

實現(xiàn)案例

這個例子基于 SpringBoot 封裝了 @ApiVersion 注解方式控制接口版本。

自定義 @ApiVersion 注解

package com.test.springboot.api.version.config.version;
import org.springframework.web.bind.annotation.Mapping;
import java.lang.annotation.*;
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Mapping
public @interface ApiVersion {
    String value();
}

定義版本匹配 RequestCondition

版本匹配支持三層版本

  • v1.1.1 (大版本.小版本.補(bǔ)丁版本)
  • v1.1 (等同于v1.1.0)
  • v1 (等同于v1.0.0)
package com.test.springboot.api.version.config.version;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.mvc.condition.RequestCondition;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Slf4j
public class ApiVersionCondition implements RequestCondition<ApiVersionCondition> {
    /**
     * support v1.1.1, v1.1, v1; three levels .
     */
    private static final Pattern VERSION_PREFIX_PATTERN_1 = Pattern.compile("/v\\d\\.\\d\\.\\d/");
    private static final Pattern VERSION_PREFIX_PATTERN_2 = Pattern.compile("/v\\d\\.\\d/");
    private static final Pattern VERSION_PREFIX_PATTERN_3 = Pattern.compile("/v\\d/");
    private static final List<Pattern> VERSION_LIST = Collections.unmodifiableList(
            Arrays.asList(VERSION_PREFIX_PATTERN_1, VERSION_PREFIX_PATTERN_2, VERSION_PREFIX_PATTERN_3)
    );
    @Getter
    private final String apiVersion;
    public ApiVersionCondition(String apiVersion) {
        this.apiVersion = apiVersion;
    }
    /**
     * method priority is higher then class.
     *
     * @param other other
     * @return ApiVersionCondition
     */
    @Override
    public ApiVersionCondition combine(ApiVersionCondition other) {
        return new ApiVersionCondition(other.apiVersion);
    }
    @Override
    public ApiVersionCondition getMatchingCondition(HttpServletRequest request) {
        for (int vIndex = 0; vIndex < VERSION_LIST.size(); vIndex++) {
            Matcher m = VERSION_LIST.get(vIndex).matcher(request.getRequestURI());
            if (m.find()) {
                String version = m.group(0).replace("/v", "").replace("/", "");
                if (vIndex == 1) {
                    version = version + ".0";
                } else if (vIndex == 2) {
                    version = version + ".0.0";
                }
                if (compareVersion(version, this.apiVersion) >= 0) {
                    log.info("version={}, apiVersion={}", version, this.apiVersion);
                    return this;
                }
            }
        }
        return null;
    }
    @Override
    public int compareTo(ApiVersionCondition other, HttpServletRequest request) {
        return compareVersion(other.getApiVersion(), this.apiVersion);
    }
    private int compareVersion(String version1, String version2) {
        if (version1 == null || version2 == null) {
            throw new RuntimeException("compareVersion error:illegal params.");
        }
        String[] versionArray1 = version1.split("\\.");
        String[] versionArray2 = version2.split("\\.");
        int idx = 0;
        int minLength = Math.min(versionArray1.length, versionArray2.length);
        int diff = 0;
        while (idx < minLength
                && (diff = versionArray1[idx].length() - versionArray2[idx].length()) == 0
                && (diff = versionArray1[idx].compareTo(versionArray2[idx])) == 0) {
            ++idx;
        }
        diff = (diff != 0) ? diff : versionArray1.length - versionArray2.length;
        return diff;
    }
}

定義 HandlerMapping

package com.test.springboot.api.version.config.version;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.lang.NonNull;
import org.springframework.web.servlet.mvc.condition.RequestCondition;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import java.lang.reflect.Method;
public class ApiVersionRequestMappingHandlerMapping extends RequestMappingHandlerMapping {
    /**
     * add @ApiVersion to controller class.
     *
     * @param handlerType handlerType
     * @return RequestCondition
     */
    @Override
    protected RequestCondition<?> getCustomTypeCondition(@NonNull Class<?> handlerType) {
        ApiVersion apiVersion = AnnotationUtils.findAnnotation(handlerType, ApiVersion.class);
        return null == apiVersion ? super.getCustomTypeCondition(handlerType) : new ApiVersionCondition(apiVersion.value());
    }
    /**
     * add @ApiVersion to controller method.
     *
     * @param method method
     * @return RequestCondition
     */
    @Override
    protected RequestCondition<?> getCustomMethodCondition(@NonNull Method method) {
        ApiVersion apiVersion = AnnotationUtils.findAnnotation(method, ApiVersion.class);
        return null == apiVersion ? super.getCustomMethodCondition(method) : new ApiVersionCondition(apiVersion.value());
    }
}

配置注冊HandlerMapping

package com.test.springboot.api.version.config.version;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

@Configuration
public class CustomWebMvcConfiguration extends WebMvcConfigurationSupport {

    @Override
    public RequestMappingHandlerMapping createRequestMappingHandlerMapping() {
        return new ApiVersionRequestMappingHandlerMapping();
    }
}

或者實現(xiàn) WebMvcRegistrations 接口

@Configuration
@RequiredArgsConstructor
public class WebConfig implements WebMvcConfigurer, WebMvcRegistrations {
    //...

    @Override
    @NonNull
    public RequestMappingHandlerMapping getRequestMappingHandlerMapping() {
        return new ApiVersionRequestMappingHandlerMapping();
    }

}

測試運行

controller

package com.test.springboot.api.version.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import tech.pdai.springboot.api.version.config.version.ApiVersion;
import tech.pdai.springboot.api.version.entity.User;

/**
 * @author farerboy
 */
@RestController
@RequestMapping("api/{v}/user")
public class UserController {

    @RequestMapping("get")
    public User getUser() {
        return User.builder().age(18).name("pdai, default").build();
    }

    @ApiVersion("1.0.0")
    @RequestMapping("get")
    public User getUserV1() {
        return User.builder().age(18).name("pdai, v1.0.0").build();
    }

    @ApiVersion("1.1.0")
    @RequestMapping("get")
    public User getUserV11() {
        return User.builder().age(19).name("pdai, v1.1.0").build();
    }

    @ApiVersion("1.1.2")
    @RequestMapping("get")
    public User getUserV112() {
        return User.builder().age(19).name("pdai2, v1.1.2").build();
    }
}

輸出

http://localhost:8080/api/v1/user/get
// {"name":"farerboy, v1.0.0","age":18}

http://localhost:8080/api/v1.1/user/get
// {"name":"farerboy, v1.1.0","age":19}

http://localhost:8080/api/v1.1.1/user/get
// {"name":"farerboy, v1.1.0","age":19} 匹配比1.1.1小的中最大的一個版本號

http://localhost:8080/api/v1.1.2/user/get
// {"name":"farerboy, v1.1.2","age":19}

http://localhost:8080/api/v1.2/user/get
// {"name":"farerboy, v1.1.2","age":19} 匹配最大的版本號,v1.1.2

這樣,如果我們向另外一個模塊提供v1版本的接口,新的需求中只變動了一個接口方法,這時候我們只需要增加一個接口添加版本號v1.1即可用v1.1版本訪問所有接口。

此外,這種方式可能會導(dǎo)致v3版本接口沒有發(fā)布,但是是可以通過v3訪問接口的;這種情況下可以添加一些限制版本的邏輯,比如最大版本,版本集合等。

到此這篇關(guān)于SpringBoot 如何實現(xiàn)多版本接口的方法步驟的文章就介紹到這了,更多相關(guān)SpringBoot 多版本接口內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • SpringBoot整合定時任務(wù)之實現(xiàn)Scheduled注解的過程(一個注解全解決)

    SpringBoot整合定時任務(wù)之實現(xiàn)Scheduled注解的過程(一個注解全解決)

    這篇文章主要介紹了SpringBoot整合定時任務(wù)之實現(xiàn)Scheduled注解的過程(一個注解全解決),本文通過使用場景分析給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2021-09-09
  • java反射_改變private中的變量及方法的簡單實例

    java反射_改變private中的變量及方法的簡單實例

    下面小編就為大家?guī)硪黄猨ava反射_改變private中的變量及方法的簡單實例。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2016-06-06
  • 一文詳解Java如何優(yōu)雅地判斷對象是否為空

    一文詳解Java如何優(yōu)雅地判斷對象是否為空

    這篇文章主要給大家介紹了關(guān)于Java如何優(yōu)雅地判斷對象是否為空的相關(guān)資料,在Java中可以使用以下方法優(yōu)雅地判斷一個對象是否為空,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2024-04-04
  • Spring Event觀察者模式事件監(jiān)聽詳解

    Spring Event觀察者模式事件監(jiān)聽詳解

    這篇文章主要介紹了Java Spring Event事件監(jiān)聽詳情解析,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價值,需要的小伙伴可以參考一下
    2022-08-08
  • 后端java壓縮圖片超詳細(xì)圖文教程

    后端java壓縮圖片超詳細(xì)圖文教程

    這篇文章主要給大家介紹了關(guān)于后端java壓縮圖片的相關(guān)資料,片壓縮是一種廣泛采用的技術(shù),它不僅能顯著減小文件大小,釋放更多存儲空間,還能提升圖片加載速度,避免長時間等待,需要的朋友可以參考下
    2024-04-04
  • 詳解Guava中EventBus的使用

    詳解Guava中EventBus的使用

    EventBus是Guava的事件處理機(jī)制,是設(shè)計模式中觀察者模式(生產(chǎn)/消費者編程模型)的優(yōu)雅實現(xiàn)。本文就來和大家聊聊EventBus的使用,需要的可以參考一下
    2022-12-12
  • 詳解Java 網(wǎng)絡(luò)IO編程總結(jié)(BIO、NIO、AIO均含完整實例代碼)

    詳解Java 網(wǎng)絡(luò)IO編程總結(jié)(BIO、NIO、AIO均含完整實例代碼)

    本篇文章主要介紹了Java 網(wǎng)絡(luò)IO編程總結(jié)(BIO、NIO、AIO均含完整實例代碼),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-12-12
  • springboot項目用maven插件打包時報錯的解決方法

    springboot項目用maven插件打包時報錯的解決方法

    文章介紹了解決Spring Boot項目使用Maven插件打包時遇到JDK版本無效問題的步驟,本文分步驟給大家介紹的非常詳細(xì),感興趣的朋友跟隨小編一起看看吧
    2026-01-01
  • 分析JVM的執(zhí)行子系統(tǒng)

    分析JVM的執(zhí)行子系統(tǒng)

    本文主要介紹了JVM執(zhí)行子系統(tǒng)。了解虛擬機(jī)是如何執(zhí)行程序的, 虛擬機(jī)怎樣運行一個Class文件的概念模型, 可以更好的理解怎樣寫出優(yōu)秀的代碼
    2021-06-06
  • SpringBoot啟動器Starters使用及原理解析

    SpringBoot啟動器Starters使用及原理解析

    這篇文章主要介紹了SpringBoot啟動器Starters使用及原理解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-04-04

最新評論

宁陵县| 平谷区| 隆昌县| 宜兴市| 铜鼓县| 木兰县| 宣武区| 买车| 科技| 民和| 五台县| 崇礼县| 瓦房店市| 确山县| 沅陵县| 兴国县| 四子王旗| 藁城市| 静安区| 利辛县| 松原市| 宁陕县| 乃东县| 沙洋县| 清苑县| 金寨县| 景洪市| 安乡县| 宁强县| 南康市| 绵阳市| 乌鲁木齐市| 和顺县| 西乌珠穆沁旗| 应用必备| 柞水县| 霍州市| 苏尼特右旗| 凤城市| 锡林郭勒盟| 桃江县|