SpringBoot版本接口

前言

为什么接口会出现多个版本

一般来说,Restful API接口是提供给其它模块,系统或是其他公司使用,不能随意频繁的变更。然而,需求和业务不断变化,接口和参数也会发生相应的变化。如果直接对原来的接口进行修改,势必会影响线其他系统的正常运行。这就必须对api 接口进行有效的版本控制。

控制接口多版本的方式

  • 相同URL,用不同的版本参数区分
    • api.demo/user?version=v1 表示 v1版本的接口, 保持原有接口不动
    • api.demo/user?version=v2 表示 v2版本的接口,更新新的接口
  • 区分不同的接口域名,不同的版本有不同的子域名, 路由到不同的实例
    • v1.api.demo/user 表示 v1版本的接口, 保持原有接口不动, 路由到instance1
    • v2.api.demo/user 表示 v2版本的接口,更新新的接口, 路由到instance2
  • 网关路由不同子目录到不同的实例(不同package也可以)
    • api.demo/v1/user 表示 v1版本的接口, 保持原有接口不动, 路由到instance1
    • api.demo/v2/user 表示 v2版本的接口,更新新的接口, 路由到instance2
  • 同一实例,用注解隔离不同版本控制
    • api.demo/v1/user 表示 v1版本的接口, 保持原有接口不动,匹配@ApiVersion("1")的handlerMapping
    • api.demo/v2/user 表示 v2版本的接口,更新新的接口,匹配@ApiVersion("2")的handlerMapping

版本定义

根据常见的三段式版本设计,版本格式定义如下x.x.x代表(大版本.小版本.补丁版本)

其中第一个 x:对应的是大版本,一般来说只有较大的改动升级,才会改变

其中第二个 x:表示正常的业务迭代版本号,每发布一个常规的 app 升级,这个数值+1

最后一个 x:主要针对 bugfix,比如发布了一个 app,结果发生了异常,需要一个紧急修复,需要再发布一个版本,这个时候可以将这个数值+1

  • v1.1.1 (大版本.小版本.补丁版本)
  • v1.1 (等同于v1.1.0)
  • v1 (等同于v1.0.0)

代码实现

定义版本枚举

public enum Versions {

    /**
     * 默认版本号
     */
    DEFAULT("1.0.0"),

    /**
     * 1.0.1
     */
    ONE_ZERO_ONE("1.0.1");

    private String value;

    Versions(String value) {
        this.value = value;
    }

    public String value() {
        return value;
    }
}

定义注解

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ApiVersion {
     
    /**
       * 版本 x.x.x格式
       *
       * @return
       */
      String value() default  Versions.DEFAULT;
}

定义版本匹配RequestCondition

public class ApiVersionCondition implements RequestCondition<ApiVersionCondition> {

  
    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;
    }

  
    @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;
    }
}

定义ApiVersionHandlerMapping

public class ApiVersionHandlerMapping extends RequestMappingHandlerMapping {

  
    @Override
    protected RequestCondition<?> getCustomTypeCondition(@NonNull Class<?> handlerType) {
        ApiVersion apiVersion = AnnotationUtils.findAnnotation(handlerType, ApiVersion.class);
        return null == apiVersion ? super.getCustomTypeCondition(handlerType) : new ApiVersionCondition(apiVersion.value());
    }

  
    @Override
    protected RequestCondition<?> getCustomMethodCondition(@NonNull Method method) {
        ApiVersion apiVersion = AnnotationUtils.findAnnotation(method, ApiVersion.class);
        return null == apiVersion ? super.getCustomMethodCondition(method) : new ApiVersionCondition(apiVersion.value());
    }
}

配置注册ApiVersionHandlerMapping

@Configuration
public class ApiVersionConfiguration extends WebMvcConfigurationSupport {

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

或者实现WebMvcRegistrations的接口

@Configuration  //如果需要配合下边的EnableApiVersion一起使用,实现版本开关控制则不需要@Configuration注解
public class ApiVersionConfiguration implements  WebMvcRegistrations {

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

}

定义EnableApiVersion

在启动类上添加这个注解后就可以开启接口的多版本支持。使用Import引入配置ApiAutoConfiguration。

/**
 * 是否开启API版本控制
 */
@Target(ElementType.TYPE)
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Import(ApiAutoConfiguration.class) //没有使用Configuration自动注入,而是使用Import带入,目的是可以在程序中选择性启用或者不启用版本控制。
public @interface EnableApiVersion {
}

测试运行

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

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

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

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

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

输出

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

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

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

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

http://localhost:8080/api/v1.2/user/get
// {"name":"张三, v1.1.2","age":19} 匹配最大的版本号,v1.1.2
posted @ 2023-05-08 10:15  leepandar  阅读(42)  评论(0编辑  收藏  举报