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
。
这种方式主要有几个缺陷:
- 通常为了统一控制,调用方会使用统一一个版本来调用接口。如果后端服务在升级接口的版本时,实际只需要变更其中几个接口的逻辑,其余接口只能通过添加新的mapping来完成升级。
- 接口的优先匹配,当调用高版本的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在初始化RequestMappingHandlerMapping
Bean的时候,会初始化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; }
当RequestMappingHandlerMapping
Bean属性初始化完成之后,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关系查询处理请求的方法
主要功能入口在AbstractHandlerMethodMapping
的lookupHandlerMethod
方法,首先根据上一节注册的@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; } }