自定义过滤器

zuul过滤器

zuul过滤器列表如下:

类型 顺序 过滤器 功能
pre -1000 PreValidateFilter (SOP自带) 校验签名
pre -998 PreLimitFilter (SOP自带) 限流拦截器
pre -3 ServletDetectionFilter 标记处理 Servlet 的类型
pre -2 Servlet30WrapperFilter 包装 HttpServletRequest 请求
pre -1 FormBodyWrapperFilter 包装请求体 Servlet30WrapperFilter
pre 1 DebugFilter 标记调试标志
pre 5 PreDecorationFilter 决定路由转发过滤器
route 10 RibbonRoutingFilter serviceId 请求转发
route 100 SimpleHostRoutingFilter url 请求转发
route 500 SendForwardFilter forward 请求转发
post 0 SendErrorFilter 处理有错误的请求响应
post 1000 SendResponseFilter 处理正常的请求响应

顺序值小的优先执行,-3之前是sop自带的过滤器,-3开始是zuul自带的过滤器。

创建自定义过滤器可以从-500开始(-1000 ~ -501留给SOP)。下面是一个自定义过虑器的例子:

  1. public class PreXXXFilter extends BaseZuulFilter {
  2. @Override
  3. protected FilterType getFilterType() {
  4. return FilterType.PRE;
  5. }
  6. @Override
  7. protected int getFilterOrder() {
  8. return -500;
  9. }
  10. @Override
  11. protected Object doRun(RequestContext requestContext) throws ZuulException {
  12. HttpServletRequest request = requestContext.getRequest();
  13. ApiParam apiParam = ZuulContext.getApiParam();
  14. String appKey = apiParam.fetchAppKey();
  15. // ...业务处理
  16. // 固定返回null
  17. return null;
  18. }
  19. }

过滤器编写完毕后,在Config中使用:

  1. @Configuration
  2. public class ZuulConfig extends AlipayZuulConfiguration {
  3. ...
  4. @Bean
  5. PreXXXFilter preXXXFilter() {
  6. return new PreXXXFilter();
  7. }
  8. ...
  9. }

spring cloud gateway

跟zuul同理

  1. public class XXXFilter implements GlobalFilter, Ordered {
  2. @Override
  3. public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
  4. ApiParam apiParam = (ApiParam)exchange.getAttribute(SopConstants.CACHE_API_PARAM);
  5. String appKey = apiParam.fetchAppKey();
  6. // ...业务处理
  7. ...
  8. return chain.filter(exchange);
  9. }
  10. @Override
  11. public int getOrder() {
  12. return -500;
  13. }
  14. }

使用过滤器:

  1. @Configuration
  2. public class GatewayConfig extends AlipayGatewayConfiguration {
  3. ...
  4. @Bean
  5. XXXFilter xxxFilter() {
  6. return new XXXFilter();
  7. }
  8. ...
  9. }