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

在移动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. angularJS 与angujs-sku实现购物车组合查询

    原网址:http://sentsin.com/web/1069.html   demo : https://codepen.io/hzxs1990225/pen/VYyOdW  修复版文件下载:htt ...

  2. 蓝桥杯 0/1背包问题 (java)

      今天第一次接触了0/1背包问题,总结一下,方便以后修改.不对的地方还请大家不啬赐教! 上一个蓝桥杯的例题: 数据规模和约定 代码: import java.util.Scanner; public ...

  3. javascript中函数的执行环境、作用域链、变量对象与活动对象

    javascript高级程序设计中:对执行环境.作用域链.变量对象.活动对象的解释: 1.执行环境: 执行环境:有时也叫环境:是JavaScript中最为重要的一个概念:执行环境定义了变量或函数有权访 ...

  4. 微信小程序实现淡入淡出效果(页面跳转)

    //目前小程序没有fadeIn(),fadeOut()方法所以还是本方法手写  <!--wxml--><!--蒙版(渐出淡去效果)--><view class=" ...

  5. Linq 实例

    1.分页 ).Take(); 2.分组 1)一般分组 //根据顾客的国家分组,查询顾客数大于5的国家名和顾客数var 一般分组 = from c in ctx.Customers group c by ...

  6. 最简单方法将项目上传到github

    准备材料: 1.首先你需要一个github账号,所有还没有的话先去注册吧!https://github.com/ 2.我们使用git需要先安装git工具,这里给出下载地址,下载后一路直接安装即可:ht ...

  7. web组件开发入门

    本文是学习慕课网阿当大话西游之WEB组件后的一个总结. 组件的分类 1 框架组件:依赖于某种框架的组件 2 定制组件:根据公司业务定制的组件 3 独立组件:不依赖框架的组件 定义和加载组件 解决css ...

  8. 【开发技术】Eclipse插件Call Hierarchy简介及设置

    Call Hierarchy 主要功能是 显示一个方法的调用层次(被哪些方法调,调了哪些方法) 在MyEclipse里Help - Software updates - Find and instal ...

  9. Maven项目pom.xml 标签含义

    project:pom.xml文件中的顶层元素: modelVersion:指明POM使用的对象模型的版本.这个值很少改动. groupId:指明创建项目的组织或者小组的唯一标识.GroupId是项目 ...

  10. MySQL的char和varchar针对空格的处理

    MySQL的char和varchar存储和查询中包含空格的实验 MySQL版本 一.测试char包含空格的存储和查询 测试发现,存储的数据,char数据类型的右侧空格存储的时候被删除了,但是左侧空格还 ...