让SpringMVC Restful API优雅地支持多版本
好久没有更新博客,难得有空,记录一下今天写的一个小工具,供有需要的朋友参考。
在移动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优雅地支持多版本的更多相关文章
- SpringMVC Restful api接口实现
[前言] 面向资源的 Restful 风格的 api 接口本着简洁,资源,便于扩展,便于理解等等各项优势,在如今的系统服务中越来越受欢迎. .net平台有WebAPi项目是专门用来实现Restful ...
- 人人都是 API 设计师:我对 RESTful API、GraphQL、RPC API 的思考
原文地址:梁桂钊的博客 博客地址:http://blog.720ui.com 欢迎关注公众号:「服务端思维」.一群同频者,一起成长,一起精进,打破认知的局限性. 有一段时间没怎么写文章了,今天提笔写一 ...
- Yii2 Restful API 原理分析
Yii2 有个很重要的特性是对 Restful API的默认支持, 通过短短的几个配置就可以实现简单的对现有Model的RESTful API 参考另一篇文章: http://www.cnblogs. ...
- Spring+SpringMVC+MyBatis+easyUI整合进阶篇(一)设计一套好的RESTful API
写在前面的话 看了一下博客目录,距离上次更新这个系列的博文已经有两个多月,并不是因为不想继续写博客,由于中间这段时间更新了几篇其他系列的文章就暂时停止了,如今已经讲述的差不多,也就继续抽时间更新< ...
- SwaggerUI+SpringMVC——构建RestFul API的可视化界面
今天给大家介绍一款工具,这个工具眼下可预见的优点是:自己主动维护最新的接口文档. 我们都知道,接口文档是非常重要的,可是随着代码的不断更新,文档却非常难持续跟着更新,今天要介绍的工具,完美的攻克了这个 ...
- Spring+SpringMVC+MyBatis+easyUI整合进阶篇(二)RESTful API实战笔记(接口设计及Java后端实现)
写在前面的话 原计划这部分代码的更新也是上传到ssm-demo仓库中,因为如下原因并没有这么做: 有些使用了该项目的朋友建议重新创建一个仓库,因为原来仓库中的项目太多,结构多少有些乱糟糟的. 而且这次 ...
- springboot集成swagger2,构建优雅的Restful API
swagger,中文“拽”的意思.它是一个功能强大的api框架,它的集成非常简单,不仅提供了在线文档的查阅,而且还提供了在线文档的测试.另外swagger很容易构建restful风格的api,简单优雅 ...
- (转)第十一篇:springboot集成swagger2,构建优雅的Restful API
声明:本部分内容均转自于方志明博友的博客,因为本人很喜欢他的博客,所以一直在学习,转载仅是记录和分享,若也有喜欢的人的话,可以去他的博客首页看:http://blog.csdn.net/forezp/ ...
- flask, SQLAlchemy, sqlite3 实现 RESTful API 的 todo list, 同时支持form操作
flask, SQLAlchemy, sqlite3 实现 RESTful API, 同时支持form操作. 前端与后台的交互都采用json数据格式,原生javascript实现的ajax.其技术要点 ...
随机推荐
- JqGrid 多行表头设置
1.我想要统计的效果是这样的 2.只要在初始化表格中加上如下代码就可以了: jQuery("#tbAbroadStatisticByUnit").jqGrid('setGroupH ...
- Proxy 那点事儿
---恢复内容开始--- 尊重原创:https://my.oschina.net/huangyong/blog/159788 Proxy,也就是"代理"了.意思就是,你不用去做,别 ...
- Eclipse安装svn插件的几种方式 转帖....
Eclipse安装svn插件的几种方式 1.在线安装: (1).点击 Help --> Install New Software... (2).在弹出的窗口中点击add按钮,输入Name(任意) ...
- 《You dont know JS》类型篇总结
类型 javaScript中的类型和熟知的一些强类型语言的有关类型的定义是不一样的.在js中,类型的含义是值的内部特征,它定义了值得行为,以使其区别于其他值.(a type is an intrins ...
- Use LiveCD to acquire images from a VM
Forensic examiners usually acquire images from suspect's PC or Laptop. What if the target computer i ...
- SVN报Previous operation has not finished; run 'cleanup'&
做着项目突然SVN报Previous operation has not finished; run 'cleanup' if it was interrupted,进度又要继续,烦.百度一下发现很多 ...
- 如何安装 Composer
下载 Composer 安装前请务必确保已经正确安装了 PHP.打开命令行窗口并执行 php -v 查看是否正确输出版本号. 打开命令行并依次执行下列命令安装最新版本的 Composer: php - ...
- PL/SQL FAQ in installation "make sure you have the 32 bits Oracle client installed" and "Database character set(AL32UTF8) and Client character set (GBK) are different"
requirement : connecting to remote oracle server . now I know the connectionURL :connectionUrl :jdb ...
- mybatis实战教程三:多对多关联
MyBatis3.0 添加了association和collection标签专门用于对多个相关实体类数据进行级联查询,但仍不支持多个相关实体类数据的级联保存和级联删除操作 一.创建student.te ...
- 简单的线性规划-scipy
根据描述,我们用线性规划带约束来求解问题 # coding=utf-8 from scipy.optimize import linprog import numpy as np def maxGai ...