让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.其技术要点 ...
随机推荐
- linux日志查看命令
tail tail 命令用于显示文本文件的末尾几行, 对于监控文件日志特别有用 tail example.txt #显示文件 example.txt 的后十行内容: tail -n 20 exampl ...
- EC+VO+SCOPE for ES3
词法环境 词法作用域 词法作用域(lexcical scope).即JavaScript变量的作用域是在定义时决定而不是执行时决定,也就是说词法作用域取决于源码. 词法环境 用于定义特定变量和函数标识 ...
- php网站在服务器上邮件发送不了,在本地可以
标签: php邮箱 2015-11-27 13:58 879人阅读 评论(0) 收藏 举报 分类: php(2) 版权声明:本文为博主原创文章,未经博主允许不得转载. 最近在做phpmailer发送邮 ...
- 解决导入MySQL数据库提示"Unknown character set: 'utf8mb4'"错误
今天老左在准备迁移公司一个客户的网站到另外一台服务器中,根据正常的操作备份最新的网页文件和导出数据库,然后在新服务器中创建站点和数据库wget迁移进去解压.因为数据库比较小,所以直接用PHPMyAdm ...
- mysql 中文乱码
- 以守护进程的方式部署flask
1.文件目录 创建一个简单的flask 项目... application = Flask(__name__) application.debug = True 2.安装wsgi pip instal ...
- SQLServer分页查询模板
SELECT TOP 10 * FROM ( SELECT ROW_NUMBER() OVER (ORDER BY id) AS RowNumber,* FROM ERPTelFile ) A WHE ...
- maven多模块搭建
此时你会发现父模块含有如下内容 这是因为创建的maven项目都带有样例,比如上图的这张图片 各种artifact都是做什么的呢,@参考文章中给出了答案 怎么创建不带这些呢? 那就创建simple pr ...
- UTF8编码
UTF-8是Unicode的实现方式之一. UTF-8最大的一个特点,就是它是一种变长的编码方式.它可以使用1~4个字节表示一个符号,根据不同的符号而变化字节长度. UTF-8的编码规则很简单,只有二 ...
- 转 intValue()的用法
intValue()是java.lang.Number类的方法,Number是一个抽象类.Java中所有的数值类都继承它. 不单是Integer有intValue方法,Double,Long等都有此方 ...