业务背景:
gateway多版本接口,在被第三方调用是发现传入的apiversion传错了,不能与代码中apiversion对应,导致调用了最老的版本接口。基于这个问题,我们准备使用apiversion就近向下调用。
实现步骤:项目启动统计所有接口对用的版本号到redis(不考虑redis服务不可用的情况),利用过滤器过滤出请求header的apiversion,通过比对将request中apiversion替换掉。
@PostMapping(value = "/doYouWant", consumes = "application/json", headers = "APIVersion=2.2")
1.统计接口对用的所有版本号,InitVersions 实现ApplicationContextAware,获取应用上下文,通过上下文获取HandlerMapping中的信息(主要是接口信息存放在RequestMappingHandlerMapping中的handlerMethods中)
package com.xxxx.client.container;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Spliterator;
import org.apache.commons.collections.SetUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.mvc.condition.HeadersRequestCondition;
import org.springframework.web.servlet.mvc.condition.NameValueExpression;
import org.springframework.web.servlet.mvc.condition.PatternsRequestCondition;
import org.springframework.web.servlet.mvc.condition.RequestMethodsRequestCondition;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import com.alibaba.fastjson.JSON;
import com.xxxx.common.util.StringTools;
import com.xxxx.common.constants.CashierStaticConstants;
import com.xxxx.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
/**
* 类职责:获取系统所有mapping的版本号<br/>
* <p>Title: InitVersions.java</p>
* <p>Description: 将所有url上的version缓存到redis</p>
* <p>Copyright: Copyright (c) 2017 xxxx信息技术有限公司</p>
* <p>Company: xxxx信息技术有限公司</p>
* <p>Author:Cent</p>
* <p>CreateTime:2019年7月22日下午5:17:34
*/
@Slf4j
@Component
public class InitVersions implements ApplicationRunner, ApplicationContextAware {
@Autowired
private RedisUtil redisUtil;
public static final double defaultApiVersion = 1.0d;
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
if (this.applicationContext == null) {
this.applicationContext = applicationContext;
}
}
@Override
public void run(ApplicationArguments args) throws Exception {
if (applicationContext == null) {
return;
}
redisUtil.removePattern(CashierStaticConstants.REDIS_API_VERSION + "*");
// 获取所有的RequestMapping
Map<String, HandlerMapping> allRequestMappings = BeanFactoryUtils
.beansOfTypeIncludingAncestors(applicationContext, HandlerMapping.class, true, false);
for (HandlerMapping handlerMapping : allRequestMappings.values()) {
// 获取RequestMappingHandlerMapping中URL映射
if (handlerMapping instanceof RequestMappingHandlerMapping) {
RequestMappingHandlerMapping requestMappingHandlerMapping = (RequestMappingHandlerMapping) handlerMapping;
Map<RequestMappingInfo, HandlerMethod> handlerMethods = requestMappingHandlerMapping
.getHandlerMethods();
ArrayList<String> patternsConditionList = new ArrayList<String>();
String servletPath = "";
ArrayList<NameValueExpression<String>> expressionList = new ArrayList<NameValueExpression<String>>();
double apiVersion = defaultApiVersion;
for (Map.Entry<RequestMappingInfo, HandlerMethod> requestMappingInfoHandlerMethodEntry : handlerMethods
.entrySet()) {
RequestMappingInfo requestMappingInfo = requestMappingInfoHandlerMethodEntry.getKey();
// servletPath
PatternsRequestCondition patternsCondition = requestMappingInfo.getPatternsCondition();
if (!CollectionUtils.isEmpty(patternsConditionList = new ArrayList(patternsCondition.getPatterns()))) {
servletPath = patternsConditionList.get(0);
} else {
log.warn("mapping中出现url为空的情况!");
continue;
}
// headers 参数
HeadersRequestCondition headersCondition = requestMappingInfo.getHeadersCondition();
Set<NameValueExpression<String>> expressions = headersCondition.getExpressions();
if (!CollectionUtils.isEmpty(expressionList = new ArrayList(expressions))
&& StringUtils.isNotBlank(expressionList.get(0).getValue())
&& StringTools.isNumeric(expressionList.get(0).getValue().trim())) {
apiVersion = new Double(expressionList.get(0).getValue().trim());
} else {
apiVersion = defaultApiVersion;
}
redisUtil.zAdd(CashierStaticConstants.REDIS_API_VERSION + servletPath.replaceAll("/", "_").toUpperCase(), apiVersion, new Double(apiVersion));
}
}
}
}
}
2.过滤器获取到request header中的apiversion和缓存对用接口的版本号比对,获得一个最后应该被调用的api
package com.xxxx.client.filter;
import java.io.IOException;
import java.util.Iterator;
import java.util.Set;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.util.CollectionUtils;
import com.xxxx.client.container.InitVersions;
import com.xxxx.client.utils.CashierHttpServletRequest;
import com.xxxx.common.constants.CashierStaticConstants;
import com.xxxx.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
/**
* 类职责:请求接口的版本号向下就近匹配<br/>
* <p>Title: ApiVersionResetFilter.java</p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2017 xxxx息技术有限公司</p>
* <p>Company: xxxx信息技术有限公司</p>
* <p>Author:Cent</p>
* <p>CreateTime:2019年7月23日上午10:10:07
*/
@Slf4j
@Order(2)
@WebFilter(urlPatterns = { "/*" }, filterName = "apiVersionResetFilter")
public class ApiVersionResetFilter implements Filter {
@Autowired
private RedisUtil redisUtil;
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
double apiVersion = 0d;
HttpServletRequest httpRequest = (HttpServletRequest) request;
CashierHttpServletRequest cashierRequest = new CashierHttpServletRequest(httpRequest);
String apiVersionString = httpRequest.getHeader(ApiVersionFilter.BODY_APIVERSION);
if(StringUtils.isBlank(apiVersionString)) {
apiVersion = InitVersions.defaultApiVersion;
} else {
apiVersion = new Double(apiVersionString);
}
Set<Double> apiVersionSet = redisUtil.zreverseRange(CashierStaticConstants.REDIS_API_VERSION + httpRequest.getServletPath().replaceAll("/", "_").toUpperCase(), 0l, -1l);
if(CollectionUtils.isEmpty(apiVersionSet)) {
log.warn("请重启服务!");
return;
}
Iterator<Double> apiVersionSetIterator = apiVersionSet.iterator();
while (apiVersionSetIterator.hasNext()) {
double optionVersion = apiVersionSetIterator.next();
if(apiVersion >= optionVersion) {
apiVersion = optionVersion;
break;
}
}
cashierRequest.putHeader(ApiVersionFilter.HEADER_APIVERSION, String.valueOf(apiVersion));
chain.doFilter(cashierRequest, response);
}
}
3.request中流数据只能被使用一个那么需要CashierHttpServletRequest中间过渡下
package com.xxxx.client.utils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.util.*;
/**
*
* 类职责: 收银台request请求 header处理
*
* Title: CashierHttpServletRequest.java
* Description:
* Copyright: Copyright (c) 2017 xxxx信息技术有限公司
* Company: xxxx信息技术有限公司
*
* @author lon.li
* @date 2018.08.23 13:53
*/
public class CashierHttpServletRequest extends HttpServletRequestWrapper {
/**
* holds custom header and value mapping
*/
private final Map< String , String > customHeaders;
public CashierHttpServletRequest ( HttpServletRequest request ) {
super(request);
this.customHeaders = new HashMap< String , String >();
}
public void putHeader( String name, String value ) {
this.customHeaders.put(name, value);
}
@Override
public String getHeader( String name ) {
// check the custom headers first
String headerValue = customHeaders.get(name);
if (headerValue != null) {
return headerValue;
}
// else return from into the original wrapped object
return ((HttpServletRequest) getRequest()).getHeader(name);
}
@Override
public Enumeration< String > getHeaderNames( ) {
// create a set of the custom header names
Set< String > set = new HashSet< String >(customHeaders.keySet());
// now add the headers from the wrapped request object
@SuppressWarnings("unchecked")
Enumeration< String > e = ((HttpServletRequest) getRequest()).getHeaderNames();
while (e.hasMoreElements()) {
// add the names of the request headers into the list
String n = e.nextElement();
set.add(n);
}
// create an enumeration from the set and return
return Collections.enumeration(set);
}
}