一、PRE Filter
前置过滤器一般用来区分请求来源、转换数据格式、debug日志、校验权限,增加请求装饰标识等待操作。
有一下几个重要方法:
(1)filterType 确定过滤器类型
(2)filterOrder 过滤器执行顺序
ServletDetectionFilter:-3
Servlet30WrapperFilter:-2
FormBodyWrapperFilter:-1
DebugFilter:1
PreDecorationFilter:5
(3)shouldFilter 是否调用run方法
(4)run 执行过滤动作
二、自定义前置过滤器
本文前置过滤器用来装饰请求,给请求参数添加version字段,请求头加过滤器类型
三、实现代码
@Component
@Slf4j
public class PreFilter extends ZuulFilter {//按类型对过滤器进行分类。Zuul中的标准类型是"pre"用于预路由筛选,"route"用于路由到原点,"post"用于后路由筛选,"error"用于错误处理。//我们还支持静态响应的"static"类型请参阅StaticResponseFilter。可以通过调用FilterProcessor.runFilters(type)//前置过滤器必须返回pre@Overridepublic String filterType() {return FilterConstants.PRE_TYPE;}//必须为过滤器定义filterOrder。如果优先级对筛选器不重要,则过滤器可能具有相同的过滤器顺序//过滤器顺序不需要是连续的@Overridepublic int filterOrder() {return FilterConstants.PRE_DECORATION_FILTER_ORDER + 10;}//默认情况下,zuulfilter是静态的;它们不携带状态。这可以通过将isStaticFilter属性重写为false来重写@Overridepublic boolean isStaticFilter() {return super.isStaticFilter();}//要禁用此筛选器的Archaius属性的名称。默认情况下,它是zuul.[classname].[filtertype].disable@Overridepublic String disablePropertyName() {return super.disablePropertyName();}//如果为true,则过滤器已被archaius禁用,不会运行@Overridepublic boolean isFilterDisabled() {return super.isFilterDisabled();}//此方法返回的"true"表示应该调用run方法//如果应该调用run方法,则返回true。false不会调用run方法@Overridepublic boolean shouldFilter() {RequestContext ctx = RequestContext.getCurrentContext();return !ctx.containsKey(FilterConstants.FORWARD_TO_KEY) // a filter has already forwarded&& !ctx.containsKey(FilterConstants.SERVICE_ID_KEY); // a filter has already determined serviceId}//如果shouldFilter方法为true,则将调用此方法。这种方法是ZuulFilter的核心方法//返回一些可以返回的任意工件。当前的实现忽略了它。//如果在执行期间发生错误,则引发ZuulException@Overridepublic Object run() throws ZuulException {RequestContext ctx = RequestContext.getCurrentContext();try {HttpServletRequest request = ctx.getRequest();ctx.addZuulRequestHeader("X-Forwarded-Filter", "pre");//header添加String method = request.getMethod();// GET请求方法if("GET".equalsIgnoreCase(method)) {Map<String, List<String>> requestQueryParams = ctx.getRequestQueryParams();if (requestQueryParams == null) {requestQueryParams = new HashMap<>();}requestQueryParams.put("version", Arrays.asList("1.0"));//添加参数ctx.setRequestQueryParams(requestQueryParams);}else if("POST".equalsIgnoreCase(method)) {//post方法String contentType = request.getContentType();if (contentType == null) {return null;}byte[] bodyBytes;MediaType mediaType = MediaType.valueOf(contentType);if(mediaType == null){return null;}if(MediaType.APPLICATION_JSON.includes(mediaType)) {//请求jsonString charset = request.getCharacterEncoding();InputStream in = ctx.getRequest().getInputStream();String body = StreamUtils.copyToString(in, Charset.forName(charset));log.info("method POST body:{}", body);Object obj = JSON.parse(body);if (obj instanceof JSONObject) {JSONObject jsonObject = (JSONObject) obj;jsonObject.put("version", "1.0");//添加参数body = jsonObject.toJSONString();}bodyBytes = body.getBytes(charset);}else if (MediaType.APPLICATION_FORM_URLENCODED.includes(mediaType)|| (request.getAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE) != null&& MediaType.MULTIPART_FORM_DATA.includes(mediaType))) {//form请求MultiValueMap<String, Object> builder = RequestContentDataExtractor.extract(request);builder.add("version", "1.0");//添加参数//转换字节流ByteArrayOutputStream output = new ByteArrayOutputStream();HttpMessageConverter converter = new AllEncompassingFormHttpMessageConverter();HttpOutputMessage httpOutputMessage = new HttpOutputMessage() {private HttpHeaders headers = new HttpHeaders();@Overridepublic HttpHeaders getHeaders() {return headers;}@Overridepublic OutputStream getBody() {return output;}};converter.write(builder, mediaType, httpOutputMessage);bodyBytes = output.toByteArray();}else {return null;}//包装新请求request = new HttpServletRequestWrapper(request) {@Overridepublic ServletInputStream getInputStream() {return new ServletInputStreamWrapper(bodyBytes);}@Overridepublic int getContentLength() {return bodyBytes.length;}@Overridepublic long getContentLengthLong() {return bodyBytes.length;}};//重写请求ctx.setRequest(request);}} catch (Exception e) {ctx.setSendZuulResponse(false);e.printStackTrace();throw new ZuulException(e, 500, "pre filter handle exception");}return null;}}