javascript
让SpringMVC Restful API优雅地支持多版本
好久沒(méi)有更新博客,難得有空,記錄一下今天寫(xiě)的一個(gè)小工具,供有需要的朋友參考。
在移動(dòng)APP開(kāi)發(fā)中,多版本接口同時(shí)存在的情況經(jīng)常發(fā)生,通常接口支持多版本,有以下兩種方式:
1.通過(guò)不同路徑區(qū)分不同版本
如:
http://www.xxx.com/api/v1/product/detail?id=100 (版本1)
http://www.xxx.com/api/v2/product/detail?id=100 (版本2)
這種情況,可以通過(guò)建立多個(gè)文件的方式實(shí)現(xiàn),優(yōu)點(diǎn)是結(jié)構(gòu)清晰、實(shí)現(xiàn)簡(jiǎn)單,缺點(diǎn)是大量重復(fù)工作導(dǎo)致實(shí)現(xiàn)不優(yōu)雅。
2.通過(guò)不同調(diào)用參數(shù)區(qū)分不同版本
如:
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還可以通過(guò)http請(qǐng)求頭的header提供】
這種方式相對(duì)靈活且優(yōu)雅,這篇文章主要討論這種方式,直接上代碼!
首先定義一個(gè)注解,用于在控制器的方法中標(biāo)記API的版本號(hào):
然后擴(kuò)展SpringMVC的RequestMappingHandlerMapping,以便于根據(jù)不同的版本號(hào),調(diào)用不同的實(shí)現(xiàn)邏輯:
?
/*** 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<>();@Overrideprotected 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);}@Overrideprotected 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;} }?
使用方式參考代碼注釋。
?
以下是用到的相關(guān)代碼:
?
/*** 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.*/@Overridepublic String getVersionCode(HttpServletRequest request) {String version = request.getHeader("version");if (!StringUtils.hasText(version)) {String versionFromUrl = request.getParameter("@version");//for debugif (StringUtils.hasText(versionFromUrl)) {version = versionFromUrl;}}return version;} }?
?
轉(zhuǎn)載于:https://www.cnblogs.com/tonymu/p/7147172.html
總結(jié)
以上是生活随笔為你收集整理的让SpringMVC Restful API优雅地支持多版本的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Cocos2d-x 常见宏
- 下一篇: 17_传智播客iOS视频教程_代码中的面