场景

在C/S架构场景中,服务端可以及时进行版本迭代更新,并且版本统一,但是客户端就存在多版本共存的情况(部分场景没法做到客户端版本强制更新),部分接口需要进行新老版本兼容,如果在接口中进行版本判断编写兼容代码的话,就比较冗余且麻烦。掌门在部分app的后端接口中是采用@ApiVersion注解实现接口版本控制的模式。

目标

1,编写一个@ApiVersion自定义注解,实现对接口进行版本控制,版本和接口对应起来

2,请求版本大于接口最大版本,走最大版本的接口;没有版本号,按默认的处理

思路

1、编写@ApiVersion注解,用于实现接口的版本控制

2、自定义RequestCondition,设置版本控制的条件

3、通过RequestMappingHandlerMapping,将对应的请求映射到有@ApiVersion注解HandlerMapping上

4、将RequestMappingHandlerMapping注册到SpringMVC容器上

5、使用和测试

依赖环境

jdk1.8

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.11</version>
        <relativePath/>
    </parent>


        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.61</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
代码编写
@ApiVersion
/**
 * 版本控制注解
 * @author 
 */
@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Mapping
public @interface ApiVersion {

    /**
     * 版本号
     * @return
     */
    String value() default "1.0.0";
}
RequestCondition
/**
 * 自定义请求条件
 * @author
 */

@AllArgsConstructor
@Getter
public class ApiVersionCondition implements RequestCondition<ApiVersionCondition> {

    private String apiVersion;

    /**
     * 定义接口时,如定义多个规则,用于判定使用那个规则
     * @param other
     * @return
     */
    @Override
    public ApiVersionCondition combine(ApiVersionCondition other) {
        // 采用最后定义优先原则,即方法上的覆盖类上面的定义
        return new ApiVersionCondition(other.getApiVersion());
    }

    /**
     * 用于进行匹配,如果匹配到了,返回对应的实例,没有,返回为空
     * @param request
     * @return
     */
    @Override
    public ApiVersionCondition getMatchingCondition(HttpServletRequest request) {
        // 获取apiversion版本,并进行解析
        String requestApiVersionStr = ApiVersionUtil.getRequestApiVersion(request);
        int reqApiVserion = ApiVersionUtil.parseVersion(requestApiVersionStr);
        int apiVersion = ApiVersionUtil.parseVersion(this.apiVersion);
        if(reqApiVserion >= apiVersion){
            return this;
        }
        return null;
    }

    /**
     * 版本排序,进行匹配,优先最新版本
     * @param other
     * @param request
     * @return
     */
    @Override
    public int compareTo(ApiVersionCondition other, HttpServletRequest request) {
        // 优先匹配最新的版本号,考虑other版本号为空时、自身版本号为空时
        if(other == null || Strings.isNullOrEmpty(other.getApiVersion())){
            return Strings.isNullOrEmpty(this.getApiVersion()) ? 0 : 1;
        }
        if(Strings.isNullOrEmpty(this.getApiVersion())){
            return -1;
        }
        int otherApiVersion = ApiVersionUtil.parseVersion(other.getApiVersion());
        int apiVersion = ApiVersionUtil.parseVersion(this.getApiVersion());
        return otherApiVersion - apiVersion;
    }
}
RequestMappingHandlerMapping
/**
 * 自定义apiVersion请求映射处理器映射器
 * @author
 */
public class ApiVersionRequestMappingHandlerMapping extends RequestMappingHandlerMapping {
   
    @Override
    protected RequestCondition<?> getCustomTypeCondition(Class<?> handlerType) {
        return createCondition(AnnotationUtils.findAnnotation(handlerType,ApiVersion.class));
    }

    @Override
    protected RequestCondition<?> getCustomMethodCondition(Method method) {
        return createCondition(AnnotationUtils.findAnnotation(method,ApiVersion.class));
    }

    private RequestCondition<ApiVersionCondition> createCondition(ApiVersion apiVersion){
        return apiVersion == null || Strings.isNullOrEmpty(apiVersion.value()) ? null : new ApiVersionCondition(apiVersion.value());
    }
}
WebMvcRegistrations
/**
 * 将自定义的apiversion请求映射处理映射器注册至springmvc容器中,发挥效果
 * @author
 */
@Configuration
@ConditionalOnWebApplication    // 表示只有springmvc存在才能注册
public class ApiVersionWebMvcRegistrationsAdapter implements WebMvcRegistrations {
    @Override
    public RequestMappingHandlerMapping getRequestMappingHandlerMapping() {
        return new ApiVersionRequestMappingHandlerMapping();
    }
}
ApiVersionUtil工具类
public class ApiVersionUtil {

    public static final String API_VERSION = "api_version";

    public static String getRequestApiVersion(HttpServletRequest request){
        String apiVersionStr = request.getHeader(API_VERSION);
        return apiVersionStr;
    }

    /**
     * 这里apiVersion 的格式统一为 1.1.1 这种格式,如果使用其它格式,也可以自行处理
     * @param apiVersionStr
     * @return
     */
    public static int parseVersion(String apiVersionStr){
        if(Strings.isNullOrEmpty(apiVersionStr)){
            return 0;
        }
        String s = apiVersionStr.replace(".", "");
        int apiVersion = Integer.parseInt(s);
        return apiVersion;
    }
}
Controller测试接口
@RestController
@Log4j2
@RequestMapping("/api/version")
public class ApiVersionController {

    @GetMapping("/test")
    public Object test(HttpServletRequest request){
        String requestApiVersion = ApiVersionUtil.getRequestApiVersion(request);
        log.info("ApiVersionController.test reqHead :{}",requestApiVersion);
        log.info("ApiVersionController.test apiVersion :{}","default");
        return "default";
    }

    @GetMapping("/test")
    @ApiVersion("1.0.1")
    public Object testV1(HttpServletRequest request){
        String requestApiVersion = ApiVersionUtil.getRequestApiVersion(request);
        log.info("ApiVersionController.testV1 reqHead :{}",requestApiVersion);
        log.info("ApiVersionController.test apiVersion :{}","1.0.1");
        return "1.0.1";
    }

    @GetMapping("/test")
    @ApiVersion("1.0.2")
    public Object testV2(HttpServletRequest request){
        String requestApiVersion = ApiVersionUtil.getRequestApiVersion(request);
        log.info("ApiVersionController.testV2 reqHead :{}",requestApiVersion);
        log.info("ApiVersionController.test apiVersion :{}","1.0.2");
        return "1.0.2";
    }
    @GetMapping("/test")
    @ApiVersion("1.0.3")
    public Object testV3(HttpServletRequest request){
        String requestApiVersion = ApiVersionUtil.getRequestApiVersion(request);
        log.info("ApiVersionController.testV3 reqHead :{}",requestApiVersion);
        log.info("ApiVersionController.test apiVersion :{}","1.0.3");
        return "1.0.3";
    }
}
测试结果

这里将请求头中的api_version和对应的请求方法的ApiVersion打印出来,方便进行判断比较

springMVC 后端接口实现Basic认证_spring

结果分析

1,如果请求头中没有传入版本号,调用没有@ApiVersion修饰的接口

2,在有定义@ApiVersion版本号在1.0.1-1.0.3中,请求头中api_version和被@@ApiVersion修饰的接口异议对应

3,如果请求头中api_version 值大于@ApiVersion定义接口的最大版本1.0.3,还是取最大版本的1.0.3接口

拓展

这种添加映射条件的方式,不光可以用来进行版本控制,比如还可以对来源判断从而进行分发等。或者,还可以考虑下能否进行接口流量限制?