说明: 创建了两个Filter,分别是
PreFilter
public class PreFilter extends ZuulFilter { public PreFilter() { super(); } @Override public String filterType() { return FilterConstants.PRE_TYPE; } @Override public int filterOrder() { return 0; } @Override public boolean shouldFilter() { // return true; //跨域设置 RequestContext ctx = RequestContext.getCurrentContext(); HttpServletRequest request = ctx.getRequest(); //只过滤OPTIONS 请求 if(request.getMethod().equals(RequestMethod.OPTIONS.name())){ return true; } return false; } @Override public Object run() { RequestContext ctx = RequestContext.getCurrentContext(); HttpServletRequest request = ctx.getRequest(); HttpServletResponse response = ctx.getResponse(); response.setHeader("Access-Control-Allow-Origin",request.getHeader("Origin")); response.setHeader("Access-Control-Allow-Credentials","true"); response.setHeader("Access-Control-Allow-Headers","authorization, content-type"); response.setHeader("Access-Control-Allow-Methods","POST,GET"); String requestUrl = request.getRequestURL().toString(); String requestUri = request.getRequestURI(); String zuul = requestUrl.substring(0,requestUrl.indexOf(requestUri)); // zuul根路径 ctx.addZuulRequestHeader("zuul", zuul); //不再路由 ctx.setSendZuulResponse(false); ctx.setResponseStatusCode(200); return null; } }
PostFilter
@Component public class PostFilter extends ZuulFilter { protected static final String SEND_ERROR_FILTER_RAN = "sendErrorFilter.ran"; @Override public String filterType() { return FilterConstants.POST_TYPE; } @Override public int filterOrder() { return -1; } @Override public boolean shouldFilter() { return true; } @Override public Object run() { return null; } }
我测试了几种情况,发现结果如下
1 按照filterType决定顺序
Pre 优先 Post执行,此时filterOrder没有作用。
2 filterType相同
filterOrder有作用,数字越小,越先执行。(负数也是这个规则,0和-1的话,-1先执行)
3 相同filterType,相同filterOrder,都执行,执行顺序不清楚。
prefilter先执行了,post后执行了。
感觉不像是按照过滤请名称排序的样子。