SpringMVC Api接口版本控制

SpringMVC Api接口版本控制

1. 问题

​ 后端服务在提供api接口时,随着业务的变化,原有的接口很有可能不能满足现有的需求。在无法修改原有接口的情况下,只能提供一个新版本的接口来开放新的业务能力。

​ 区分不同版本的api接口的方式有多种,其中一种简单通用的方式是在uri中添加版本的标识,例如/api/v1/user,api/v3/user。通过v+版本号来指定不同版本的api接口。在后端服务的代码中,可以将版本号直接写入代码中,例如,user接口提供两个入口方法,url mapping分别指定为/api/v1/user/api/v2/user

这种方式主要有几个缺陷:

  1. 通常为了统一控制,调用方会使用统一一个版本来调用接口。如果后端服务在升级接口的版本时,实际只需要变更其中几个接口的逻辑,其余接口只能通过添加新的mapping来完成升级。
  2. 接口的优先匹配,当调用高版本的api接口时,理论应该访问当前最高版本的接口,例如,如果当前整体api版本为4,但是实际上/user接口的mapping配置最高版本为v2,这时使用v4或者v2调用/user接口时,都应该返回/v2/user的结果。

2. 解决方式

​ 为了较好地解决上面的问题,需要从SpringMVC对uri映射到接口的逻辑做一个扩展。

2.1 SpringMVC映射请求到处理方法的过程

​ SpringMVC处理请求分发的过程中主要的几个类为:

HandlerMapping: 定义根据请求获取处理当期请求的HandlerChain的getHandler方法,其中包括实际处理逻辑的handler对象和拦截器

AbstractHandlerMapping: 实现HandlerMapping接口的抽象类,在getHandler方法实现了拦截器的初始化和handler对象获取,其中获取handler对象的getHandlerInternal方法为抽象方法,由子类实现

AbstractHandlerMethodMapping<T>: 继承AbstractHandlerMapping,定义了method handler映射关系,每一个method handler都一个唯一的T关联

RequestMappingInfoHandlerMapping: 继承``AbstractHandlerMethodMapping<RequestMappingInfo>`,定义了RequestMappingInfo与method handler的关联关系

RequestMappingInfo: 包含各种匹配规则RequestCondition,请求到method的映射规则信息都包含在这个对象中,

Condition 说明
PatternsRequestCondition url匹配规则
RequestMethodsRequestCondition http方法匹配规则,例如GET,POST等
ParamsRequestCondition 参数匹配规则
HeadersRequestCondition http header匹配规则
ConsumesRequestCondition 请求Content-Type头部的媒体类型匹配规则
ProducesRequestCondition 请求Accept头部媒体类型匹配规则
RequestCondition 自定义condition

RequestMappingHandlerMapping: 继承RequestMappingInfoHandlerMapping,处理方法的@ReqeustMapping注解,将其与method handler与@ReqeustMapping注解构建的RequestMappingInfo关联

2.1.1 Spring初始化RequestMappingInfo与handler的关系

​ Spring在初始化RequestMappingHandlerMappingBean的时候,会初始化Controller的方法与RequestMappingInfo的映射关系并缓存,方便请求过来时,查询使用。

RequestMappingHandlerMapping实现了InitializingBean接口(父类实现),接口说明如下:

/**
 * Interface to be implemented by beans that need to react once all their
 * properties have been set by a BeanFactory: for example, to perform custom
 * initialization, or merely to check that all mandatory properties have been set.
 */
public interface InitializingBean {
    /**
     * BeanFactory初始化bean的属性完成后会调用当前方法
     */
    void afterPropertiesSet() throws Exception;
}

​ 当RequestMappingHandlerMappingBean属性初始化完成之后,BeanFactory对调用afterPropertiesSet方法:

    @Override
    public void afterPropertiesSet() {
        //初始化handler methods
        initHandlerMethods();
    }

    protected void initHandlerMethods() {
        ...
        // 查询所有bean,分别检测是否有@Controller和@RequestMapping配置
        String[] beanNames = (this.detectHandlerMethodsInAncestorContexts ?
                BeanFactoryUtils.beanNamesForTypeIncludingAncestors(obtainApplicationContext(), Object.class) :
                obtainApplicationContext().getBeanNamesForType(Object.class));

        for (String beanName : beanNames) {
            if (!beanName.startsWith(SCOPED_TARGET_NAME_PREFIX)) {
                Class<?> beanType = null;
                try {
                    beanType = obtainApplicationContext().getType(beanName);
                }
                catch (Throwable ex) {
                    // An unresolvable bean type, probably from a lazy bean - let's ignore it.
                    if (logger.isDebugEnabled()) {
                        logger.debug("Could not resolve target class for bean with name '" + beanName + "'", ex);
                    }
                }
                // 只处理注解了@Controller或@RequestMapping,@RestController、@GetMapping等也
                // 符合条件
                if (beanType != null && isHandler(beanType)) {
                    // 检测Mapping并注册
                    detectHandlerMethods(beanName);
                }
            }
        }
        // 空实现
        handlerMethodsInitialized(getHandlerMethods());
    }

detectHandlerMethods方法会将Controller中所以可以检测到RequestCondition的方法抽取出来,并将包含RequestCondition集合的对象RequestMappingInfo一起注册,RequestCondition集合包括所有配置的规则,例如:

@RequestMapping(value = "/test", method = RequestMethod.GET, consumes = MediaType.APPLICATION_JSON_VALUE)

detectHandlerMethods方法:

    protected void detectHandlerMethods(final Object handler) {
        // handlerType有可能是beanName,获取bean实例
        Class<?> handlerType有可能是beanName = (handler instanceof String ?
                obtainApplicationContext().getType((String) handler) : handler.getClass());

        if (handlerType != null) {
            // 获取实际的Controller Class对象,处理CGLIB代理类的情况,拿到被代理的Class对象
            final Class<?> userType = ClassUtils.getUserClass(handlerType);
            Map<Method, T> methods = MethodIntrospector.selectMethods(userType,
                    (MethodIntrospector.MetadataLookup<T>) method -> {
                        try {
                            // 实际获取RequestMappingInfo
                            return getMappingForMethod(method, userType);
                        }
                        catch (Throwable ex) {
                            throw new IllegalStateException("Invalid mapping on handler class [" +
                                    userType.getName() + "]: " + method, ex);
                        }
                    });
            if (logger.isDebugEnabled()) {
                logger.debug(methods.size() + " request handler methods found on " + userType + ": " + methods);
            }
            methods.forEach((method, mapping) -> {
                Method invocableMethod = AopUtils.selectInvocableMethod(method, userType);
                // 注册RequestMappingInfo和method的关联关系
                registerHandlerMethod(handler, invocableMethod, mapping);
            });
        }
    }

getMappingForMethod方法中,将方法与类中的@RequestMapping注解信息结合,同时获取用户自定义的RequestCondition,将所有的condition组合成一个RequestMappingInfo返回,获取不到则返回null。

    protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) {
        // 获取方法的RequestMappingInfo,包括自定义的RequestCondition
        RequestMappingInfo info = createRequestMappingInfo(method);
        if (info != null) {
            // 获取类的RequestMappingInfo,包括自定义的RequestCondition
            RequestMappingInfo typeInfo = createRequestMappingInfo(handlerType);
            if (typeInfo != null) {
                info = typeInfo.combine(info);
            }
        }
        return info;
    }
    // 获取RequestMappingInfo
    private RequestMappingInfo createRequestMappingInfo(AnnotatedElement element) {
        // 获取@RequestMapping注解
        RequestMapping requestMapping = AnnotatedElementUtils.findMergedAnnotation(element, RequestMapping.class);
        // 获取自定义的RequestCondition
        RequestCondition<?> condition = (element instanceof Class ?
                getCustomTypeCondition((Class<?>) element) : getCustomMethodCondition((Method) element));
        // 组合自定义的RequestCondition与@RequestMapping的信息返回RequestMappingInfo
        return (requestMapping != null ? createRequestMappingInfo(requestMapping, condition) : null);
    }
2.1.2 Spring根据mapping关系查询处理请求的方法

​ 主要功能入口在AbstractHandlerMethodMappinglookupHandlerMethod方法,首先根据上一节注册的@RequestMapping配置的uri直接查询是否有对应的处理方法,如果查询不到,例如url配置中有占位符,不能直接匹配上,则遍历Mapping缓存查询:

    protected HandlerMethod lookupHandlerMethod(String lookupPath, HttpServletRequest request) throws Exception {
        List<Match> matches = new ArrayList<>();
        // 1.直接根据url查询关联
        List<T> directPathMatches = this.mappingRegistry.getMappingsByUrl(lookupPath);
        if (directPathMatches != null) {
            addMatchingMappings(directPathMatches, matches, request);
        }
        if (matches.isEmpty()) {
            // 2.直接根据url查询不到,遍历映射缓存,确认是否有匹配的handler方法
            addMatchingMappings(this.mappingRegistry.getMappings().keySet(), matches, request);
        }
        // 3.如果有多个匹配,根据规则做一个排序,拿最佳匹配的handler,如果无法区分就会报错
        ...
    }

​ 在步骤2中,会将缓存中的RequestMappingInfo查询出来,并对当前HttpServletRequest做一个匹配,主要逻辑是使用RequestMappingInfo中保存的各种RequestCondition匹配当前请求,也包括自定义的RequestCondition,返回匹配结果,主要的方法为RequestMappingInfo的getMatchingCondition

    public RequestMappingInfo getMatchingCondition(HttpServletRequest request) {
        // 使用当前对象保存的RequestMethodsRequestCondition信息匹配request
        RequestMethodsRequestCondition methods = this.methodsCondition.getMatchingCondition(request);
        // 使用当前对象保存的ParamsRequestCondition信息匹配request
        ParamsRequestCondition params = this.paramsCondition.getMatchingCondition(request);
        HeadersRequestCondition headers = this.headersCondition.getMatchingCondition(request);
        ConsumesRequestCondition consumes = this.consumesCondition.getMatchingCondition(request);
        ProducesRequestCondition produces = this.producesCondition.getMatchingCondition(request);

        if (methods == null || params == null || headers == null || consumes == null || produces == null) {
            return null;
        }

        PatternsRequestCondition patterns = this.patternsCondition.getMatchingCondition(request);
        if (patterns == null) {
            return null;
        }
        // 使用当前对象保存的自定义的RequestCondition信息匹配request
        RequestConditionHolder custom = this.customConditionHolder.getMatchingCondition(request);
        if (custom == null) {
            return null;
        }
        // 如果匹配,返回匹配的结果
        return new RequestMappingInfo(this.name, patterns,
                methods, params, headers, consumes, produces, custom.getCondition());
    }

​ 将请求分发到具体的Controller方法的逻辑主要是初始化过程中注册的Mapping缓存(RequestMappingInfo)查找与匹配的过程,RequestMappingInfo中包含各种RequestCondition,包括参数、HTTP方法、媒体类型等规则的匹配,同时还包含了一个自定义的RequestCondition的扩展,如果想要增加自定义的Request匹配规则,就可以从这里入手。

2.2 自定义RequestCondition实现版本控制

​ RequestCondition定义:

public interface RequestCondition<T> {
    /**
     * 同另一个condition组合,例如,方法和类都配置了@RequestMapping的url,可以组合
     */
    T combine(T other);
    /**
     * 检查request是否匹配,可能会返回新建的对象,例如,如果规则配置了多个模糊规则,可能当前请求
     * 只满足其中几个,那么只会返回这几个条件构建的Condition
     */
    @Nullable
    T getMatchingCondition(HttpServletRequest request);
    /**
     * 比较,请求同时满足多个Condition时,可以区分优先使用哪一个
     */
    int compareTo(T other, HttpServletRequest request);
}

​ 同@RequestMapping一样,我们同样定义一个自定义注解,来保存接口方法的规则信息:

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ApiVersion {
    // 定义接口的版本号
    int value() default 1;
}

​ 自定义一个新的RequestCondition:

public class ApiVersionRequestCondition implements RequestCondition<ApiVersionRequestCondition> {
    // 用于匹配request中的版本号  v1 v2
    private static final Pattern VERSION_PATTERN = Pattern.compile("/v(\\d+).*");
    // 保存当前的版本号
    private int version;
    // 保存所有接口的最大版本号
    private static int maxVersion = 1;

    public ApiVersionRequestCondition(int version) {
        this.version = version;
    }

    @Override
    public ApiVersionRequestCondition combine(ApiVersionRequestCondition other) {
        // 上文的getMappingForMethod方法中是使用 类的Condition.combine(方法的condition)的结果
        // 确定一个方法的condition,所以偷懒的写法,直接返回参数的版本,可以保证方法优先,可以优化
        // 在condition中增加一个来源于类或者方法的标识,以此判断,优先整合方法的condition
        return new ApiVersionRequestCondition(other.version);
    }

    @Override
    public ApiVersionRequestCondition getMatchingCondition(HttpServletRequest request) {
        // 正则匹配请求的uri,看是否有版本号 v1
        Matcher matcher = VERSION_PATTERN.matcher(request.getRequestURI());
        if (matcher.find()) {
            String versionNo = matcher.group(1);
            int version = Integer.valueOf(versionNo);
            // 超过当前最大版本号或者低于最低的版本号均返回不匹配
            if (version <= maxVersion && version >= this.version) {
                return this;
            }
        }
        return null;
    }

    @Override
    public int compareTo(ApiVersionRequestCondition other, HttpServletRequest request) {
        // 以版本号大小判定优先级,越高越优先
        return other.version - this.version;
    }

    public int getVersion() {
        return version;
    }

    public static void setMaxVersion(int maxVersion) {
        ApiVersionRequestCondition.maxVersion = maxVersion;
    }
}

​ 因为默认的RequestMappingHandlerMapping实现只有一个空的获取自定义RequestCondition的实现,所以需要继承实现:

public class ApiHandlerMapping extends RequestMappingHandlerMapping {

    private int latestVersion = 1;

    @Override
    protected RequestCondition<?> getCustomTypeCondition(Class<?> handlerType) {
        // 判断是否有@ApiVersion注解,构建基于@ApiVersion的RequestCondition
        ApiVersionRequestCondition condition = buildFrom(AnnotationUtils.findAnnotation(handlerType, ApiVersion.class));
        // 保存最大版本号
        if (condition != null && condition.getVersion() > latestVersion) {
            ApiVersionRequestCondition.setMaxVersion(condition.getVersion());
        }
        return condition;
    }

    @Override
    protected RequestCondition<?> getCustomMethodCondition(Method method) {
        // 判断是否有@ApiVersion注解,构建基于@ApiVersion的RequestCondition
        ApiVersionRequestCondition condition =  buildFrom(AnnotationUtils.findAnnotation(method, ApiVersion.class));
        // 保存最大版本号
        if (condition != null && condition.getVersion() > latestVersion) {
            ApiVersionRequestCondition.setMaxVersion(condition.getVersion());
        }
        return condition;
    }

    private ApiVersionRequestCondition buildFrom(ApiVersion apiVersion) {
        return apiVersion == null ? null : new ApiVersionRequestCondition(apiVersion.value());
    }
}

​ 在SpringBoot项目中增加Config,注入自定义的ApiHandlerMapping:

@Configuration
public class Config extends WebMvcConfigurationSupport {
    @Override
    public RequestMappingHandlerMapping requestMappingHandlerMapping() {
        ApiHandlerMapping handlerMapping = new ApiHandlerMapping();
        handlerMapping.setOrder(0);
        handlerMapping.setInterceptors(getInterceptors());
        return handlerMapping;
    }
}

​ 自定义Contoller测试:

@RestController
@ApiVersion
// 在url中增加一个占位符,用于匹配未知的版本 v1 v2...
@RequestMapping("/api/{version}")
public class Controller {

    @GetMapping("/user/{id}")
    @ApiVersion(2)
    public Result<User> getUser(@PathVariable("id") String id) {
        return new Result<>("0", "get user V2 :" + id, new User("user2_" + id, 20));
}

    @GetMapping("/user/{id}")
    @ApiVersion(4)
    public Result<User> getUserV4(@PathVariable("id") String id) {
        return new Result<>("0", "get user V4 :" + id, new User("user4_" + id, 20));
    }

    @GetMapping("/cat/{id}")
    public Result<User> getCatV1(@PathVariable("id") String id) {
        return new Result<>("0", "get cat V1 :" + id, new User("cat1_" + id, 20));
    }

    @GetMapping("/dog/{id}")
    public Result<User> getDogV1(@PathVariable("id") String id) {
        return new Result<>("0", "get dog V3 :" + id, new User("dog1_" + id, 20));
    }
}

// Result定义
public class Result<T> {
    private String code;
    private String msg;
    private T data;

    public Result() {
    }

    public Result(String code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }
}

​ 项目启动后,访问接口请求:

/api/v1/user/123

result: 404

/api/v2/user/123

result: {"code":"0","msg":"get user V2 :123","data":{"name":"user2_123","age":20}}

/api/v3/user/123

result: {"code":"0","msg":"get user V2 :123","data":{"name":"user2_123","age":20}}

/api/v4/user/123

result: {"code":"0","msg":"get user V4 :123","data":{"name":"user4_123","age":20}}

/api/v5/user/123

result: 404

/api/v1/cat/123

result: {"code":"0","msg":"get cat V1 :123","data":{"name":"cat1_123","age":20}}

/api/v2/cat/123

result: 404

/api/v1/dog/123

result: {"code":"0","msg":"get dog V3 :123","data":{"name":"dog1_123","age":20}}

/api/v2/dog/123

result: 404

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 160,646评论 4 366
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,979评论 1 301
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 110,391评论 0 250
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,356评论 0 215
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,740评论 3 293
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,836评论 1 224
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 32,022评论 2 315
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,764评论 0 204
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,487评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,728评论 2 252
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,200评论 1 263
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,548评论 3 260
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,217评论 3 241
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,134评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,921评论 0 201
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,919评论 2 283
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,766评论 2 274

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 170,585评论 25 707
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,105评论 18 139
  • 朋友推荐此类软件,却随心的看上这个,那就写点什么吧。 又是一年退伍季,不知道为什么心里并没有那么伤感,哈哈哈哈,属...
    Erza宋宋阅读 187评论 0 0
  • 在iOS中如果要使用类似安卓中的RadioButton,就会发现比较麻烦,因为在iOS中没有自带的RadioBut...
    王韩峰阅读 821评论 1 9
  • 网友都说这是一部不适合现任一起观看的电影,但你们无所谓。 毕竟,你们成为彼此的“现任”,还不到一个季节。从张灯结彩...
    蛎子阅读 407评论 0 0