好久没有更新博客,难得有空,记录一下今天写的一个小工具,供有需要的朋友参考。

在移动APP开发中,多版本接口同时存在的情况经常发生,通常接口支持多版本,有以下两种方式:

1.通过不同路径区分不同版本

如:

http://www.xxx.com/api/v1/product/detail?id=100 (版本1)
http://www.xxx.com/api/v2/product/detail?id=100 (版本2)

这种情况,可以通过建立多个文件的方式实现,优点是结构清晰、实现简单,缺点是大量重复工作导致实现不优雅。

2.通过不同调用参数区分不同版本

如:
http://www.xxx.com/api/v1/product/detail?id=100&@version=1(版本1)
http://www.xxx.com/api/v1/product/detail?id=100&@version=2(版本2)

【version还可以通过http请求头的header提供】

这种方式相对灵活且优雅,这篇文章主要讨论这种方式,直接上代码!

首先定义一个注解,用于在控制器的方法中标记API的版本号:

/**
* Annotation for support Multi-version Restful API
*
* @author Tony Mu(tonymu@qq.com)
* @since 2017-07-07
*/
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Mapping
public @interface ApiVersion { /**
* api version code
*/
double value() default 1.0; }

然后扩展SpringMVC的RequestMappingHandlerMapping,以便于根据不同的版本号,调用不同的实现逻辑:

/**
* Custom RequestMappingHandlerMapping for support multi-version of spring mvc restful api with same url.
* Version code provide by {@code ApiVersionCodeDiscoverer}.
* <p>
*
* How to use ?
*
* Spring mvc config case:
*
* <pre class="code">
* @Configuration
* public class WebConfig extends WebMvcConfigurationSupport {
* @Override protected RequestMappingHandlerMapping createRequestMappingHandlerMapping() {
* MultiVersionRequestMappingHandlerMapping requestMappingHandlerMapping = new MultiVersionRequestMappingHandlerMapping();
* requestMappingHandlerMapping.registerApiVersionCodeDiscoverer(new DefaultApiVersionCodeDiscoverer());
* return requestMappingHandlerMapping;
* }
* }</pre>
*
* Controller/action case:
*
* <pre class="code">
* @RestController
* @RequestMapping(value = "/api/product")
* public class ProductController {
*
* @RequestMapping(value = "detail", method = GET)
* public something detailDefault(int id) {
* return something;
* }
*
* @RequestMapping(value = "detail", method = GET)
* @ApiVersion(value = 1.1)
* public something detailV11(int id) {
* return something;
* }
*
* @RequestMapping(value = "detail", method = GET)
* @ApiVersion(value = 1.2)
* public something detailV12(int id) {
* return something;
* }
* }</pre>
*
* Client case:
*
* <pre class="code">
* $.ajax({
* type: "GET",
* url: "http://www.xxx.com/api/product/detail?id=100",
* headers: {
* value: 1.1
* },
* success: function(data){
* do something
* }
* });</pre>
*
* @since 2017-07-07
*/
public class MultiVersionRequestMappingHandlerMapping extends RequestMappingHandlerMapping { private static final Logger logger = LoggerFactory.getLogger(MultiVersionRequestMappingHandlerMapping.class); private final static Map<String, HandlerMethod> HANDLER_METHOD_MAP = new HashMap<>(); /**
* key pattern,such as:/api/product/detail[GET]@1.1
*/
private final static String HANDLER_METHOD_KEY_PATTERN = "%s[%s]@%s"; private List<ApiVersionCodeDiscoverer> apiVersionCodeDiscoverers = new ArrayList<>(); @Override
protected void registerHandlerMethod(Object handler, Method method, RequestMappingInfo mapping) {
ApiVersion apiVersionAnnotation = method.getAnnotation(ApiVersion.class);
if (apiVersionAnnotation != null) {
registerMultiVersionApiHandlerMethod(handler, method, mapping, apiVersionAnnotation);
return;
}
super.registerHandlerMethod(handler, method, mapping);
} @Override
protected HandlerMethod lookupHandlerMethod(String lookupPath, HttpServletRequest request) throws Exception {
HandlerMethod restApiHandlerMethod = lookupMultiVersionApiHandlerMethod(lookupPath, request);
if (restApiHandlerMethod != null)
return restApiHandlerMethod;
return super.lookupHandlerMethod(lookupPath, request);
} public void registerApiVersionCodeDiscoverer(ApiVersionCodeDiscoverer apiVersionCodeDiscoverer){
if(!apiVersionCodeDiscoverers.contains(apiVersionCodeDiscoverer)){
apiVersionCodeDiscoverers.add(apiVersionCodeDiscoverer);
}
} private void registerMultiVersionApiHandlerMethod(Object handler, Method method, RequestMappingInfo mapping, ApiVersion apiVersionAnnotation) {
PatternsRequestCondition patternsCondition = mapping.getPatternsCondition();
RequestMethodsRequestCondition methodsCondition = mapping.getMethodsCondition();
if (patternsCondition == null
|| methodsCondition == null
|| patternsCondition.getPatterns().size() == 0
|| methodsCondition.getMethods().size() == 0) {
return;
}
Iterator<String> patternIterator = patternsCondition.getPatterns().iterator();
Iterator<RequestMethod> methodIterator = methodsCondition.getMethods().iterator();
while (patternIterator.hasNext() && methodIterator.hasNext()) {
String patternItem = patternIterator.next();
RequestMethod methodItem = methodIterator.next();
String key = String.format(HANDLER_METHOD_KEY_PATTERN, patternItem, methodItem.name(), apiVersionAnnotation.value());
HandlerMethod handlerMethod = super.createHandlerMethod(handler, method);
if (!HANDLER_METHOD_MAP.containsKey(key)) {
HANDLER_METHOD_MAP.put(key, handlerMethod);
if (logger.isDebugEnabled()) {
logger.debug("register ApiVersion HandlerMethod of %s %s", key, handlerMethod);
}
}
}
} private HandlerMethod lookupMultiVersionApiHandlerMethod(String lookupPath, HttpServletRequest request) {
String version = tryResolveApiVersion(request);
if (StringUtils.hasText(version)) {
String key = String.format(HANDLER_METHOD_KEY_PATTERN, lookupPath, request.getMethod(), version);
HandlerMethod handlerMethod = HANDLER_METHOD_MAP.get(key);
if (handlerMethod != null) {
if (logger.isDebugEnabled()) {
logger.debug("lookup ApiVersion HandlerMethod of %s %s", key, handlerMethod);
}
return handlerMethod;
}
logger.debug("lookup ApiVersion HandlerMethod of %s failed", key);
}
return null;
} private String tryResolveApiVersion(HttpServletRequest request) {
for (int i = 0; i < apiVersionCodeDiscoverers.size(); i++) {
ApiVersionCodeDiscoverer apiVersionCodeDiscoverer = apiVersionCodeDiscoverers.get(i);
String versionCode = apiVersionCodeDiscoverer.getVersionCode(request);
if(StringUtils.hasText(versionCode))
return versionCode;
}
return null;
}
}

使用方式参考代码注释。

以下是用到的相关代码:

/**
* Interface to discover api version code in http request.
*
* @author Tony Mu(tonymu@qq.com)
* @since 2017-07-11
*/
public interface ApiVersionCodeDiscoverer { /**
* Return an api version code that can indicate the version of current api.
*
* @param request current HTTP request
* @return an api version code that can indicate the version of current api or {@code null}.
*/
String getVersionCode(HttpServletRequest request); }
/**
* Default implementation of the {@link ApiVersionCodeDiscoverer} interface, get api version code
* named "version" in headers or named "@version" in parameters.
*
* @author Tony Mu(tonymu@qq.com)
* @since 2017-07-11
*/
public class DefaultApiVersionCodeDiscoverer implements ApiVersionCodeDiscoverer { /**
* Get api version code named "version" in headers or named "@version" in parameters.
*
* @param request current HTTP request
* @return api version code named "version" in headers or named "@version" in parameters.
*/
@Override
public String getVersionCode(HttpServletRequest request) {
String version = request.getHeader("version");
if (!StringUtils.hasText(version)) {
String versionFromUrl = request.getParameter("@version");//for debug
if (StringUtils.hasText(versionFromUrl)) {
version = versionFromUrl;
}
}
return version;
}
}

让SpringMVC Restful API优雅地支持多版本的更多相关文章

  1. SpringMVC Restful api接口实现

    [前言] 面向资源的 Restful 风格的 api 接口本着简洁,资源,便于扩展,便于理解等等各项优势,在如今的系统服务中越来越受欢迎. .net平台有WebAPi项目是专门用来实现Restful ...

  2. 人人都是 API 设计师:我对 RESTful API、GraphQL、RPC API 的思考

    原文地址:梁桂钊的博客 博客地址:http://blog.720ui.com 欢迎关注公众号:「服务端思维」.一群同频者,一起成长,一起精进,打破认知的局限性. 有一段时间没怎么写文章了,今天提笔写一 ...

  3. Yii2 Restful API 原理分析

    Yii2 有个很重要的特性是对 Restful API的默认支持, 通过短短的几个配置就可以实现简单的对现有Model的RESTful API 参考另一篇文章: http://www.cnblogs. ...

  4. Spring+SpringMVC+MyBatis+easyUI整合进阶篇(一)设计一套好的RESTful API

    写在前面的话 看了一下博客目录,距离上次更新这个系列的博文已经有两个多月,并不是因为不想继续写博客,由于中间这段时间更新了几篇其他系列的文章就暂时停止了,如今已经讲述的差不多,也就继续抽时间更新< ...

  5. SwaggerUI+SpringMVC——构建RestFul API的可视化界面

    今天给大家介绍一款工具,这个工具眼下可预见的优点是:自己主动维护最新的接口文档. 我们都知道,接口文档是非常重要的,可是随着代码的不断更新,文档却非常难持续跟着更新,今天要介绍的工具,完美的攻克了这个 ...

  6. Spring+SpringMVC+MyBatis+easyUI整合进阶篇(二)RESTful API实战笔记(接口设计及Java后端实现)

    写在前面的话 原计划这部分代码的更新也是上传到ssm-demo仓库中,因为如下原因并没有这么做: 有些使用了该项目的朋友建议重新创建一个仓库,因为原来仓库中的项目太多,结构多少有些乱糟糟的. 而且这次 ...

  7. springboot集成swagger2,构建优雅的Restful API

    swagger,中文“拽”的意思.它是一个功能强大的api框架,它的集成非常简单,不仅提供了在线文档的查阅,而且还提供了在线文档的测试.另外swagger很容易构建restful风格的api,简单优雅 ...

  8. (转)第十一篇:springboot集成swagger2,构建优雅的Restful API

    声明:本部分内容均转自于方志明博友的博客,因为本人很喜欢他的博客,所以一直在学习,转载仅是记录和分享,若也有喜欢的人的话,可以去他的博客首页看:http://blog.csdn.net/forezp/ ...

  9. flask, SQLAlchemy, sqlite3 实现 RESTful API 的 todo list, 同时支持form操作

    flask, SQLAlchemy, sqlite3 实现 RESTful API, 同时支持form操作. 前端与后台的交互都采用json数据格式,原生javascript实现的ajax.其技术要点 ...

随机推荐

  1. 《SpringMVC从入门到放肆》五、SpringMVC配置式开发(处理器适配器)

    上一篇我们大致讲解了处理器映射器的处理流程以及跟了一下源码的执行流程.今天我们来了解一下处理器适配器. 一.适配器模式 在阎宏博士的<JAVA与模式>一书中开头是这样描述适配器(Adapt ...

  2. JavaScript八张思维导图—操作符

    JS基本概念 JS操作符 JS基本语句 JS数组用法 Date用法 JS字符串用法 JS编程风格 JS编程实践 不知不觉做前端已经五年多了,无论是从最初的jQuery还是现在火热的Angular,Vu ...

  3. 解决mysql不是内部或外部命令

    安装Mysql后,当我们在cmd中敲入mysql时会出现'Mysql'不是内部或外部命令,也不是可运行的程序或其处理文件. 工具/原料 mysql cmd 方法/步骤 1 打开我的电脑在我的电脑右键中 ...

  4. LAMP环境跟LNMP环境有什么不同,主要用什么地方

    LAMP即Linux+Apache+Mysql/MariaDB+Perl/PHP/Python Linux+Apache+Mysql/MariaDB+Perl/PHP/Python一组常用来搭建动态网 ...

  5. JAVA WEB之Spring4.x JdbcTemplate

    jdbcTemplate 说白了,他就是Spring提供用于简化数据库访问的类 基本jdbc驱动访问数据库 /* 一个简易好用的数据库连接和访问类 */ package cslg.cn.control ...

  6. 全栈开发之HTML快速入门(一)

    一.HTML 是什么? HTML 指的是超文本标记语言 (Hyper Text Markup Language) HTML 不是一种编程语言,而是一种标记语言 (markup language) 标记 ...

  7. 修改Weblogic jdk版本

    找到 F:\Oracle\Middleware\Oracle_Home\user_projects\domains\base_domain\bin setDomainEnv.cmd

  8. [转]另一种遍历Map的方式: Map.Entry 和 Map.entrySet()

    转自: http://blog.csdn.net/mageshuai/article/details/3523116 今天看Think in java 的GUI这一章的时候,里面的TextArea这个 ...

  9. JavaScript return 最简单解释

    一.return 返回值 1)函数名字 +括号 :fun() ==> retrun 后面的值 2)所以函数的模范返回值是为未定义 3)return; 后面的任何代码都不会执行了 二.arguem ...

  10. XML,HTML,XHTML

    对于上面3种技术,我们经常使用到,这里具体的做一个总结,来对比一下这3个东西. 什么是XML? XML即Extentsible Markup Language(可扩展标记语言),是用来定义其它语言的一 ...