spring cloud gateway 某些路由中跳过全局过滤器

在Spring Cloud Gateway中GlobalFilter可以方便的全局拦截或统计,有时候希望在某些路由中可以跳过GlobalFilter,可以通过GatewayFilter与GlobalFilter组合来实现。

1. 新建项目

新建一个 Spring Cloud Gateway的项目,添加对应的依赖

2. GlobalFilter

https://www.jianshu.com/p/42455cdc6d25

@Component
public class TestGlobalFilter implements GlobalFilter, Ordered {
    public final static String ATTRIBUTE_IGNORE_TEST_GLOBAL_FILTER = "@ignoreTestGlobalFilter";

    @Override
    public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //跳过检测
        if (exchange.getAttribute(ATTRIBUTE_IGNORE_TEST_GLOBAL_FILTER) != null) {
            return chain.filter(exchange);
        } else {
            //简单增加一个参数
            URI uri = exchange.getRequest().getURI();
            String query = uri.getRawQuery();
            if (StringUtils.hasText(query)) {
                query = query + "&throwFilter=true";
            } else {
                query = query + "?throwFilter=true";
            }

            URI newUri = UriComponentsBuilder.fromUri(uri)
                    .replaceQuery(query)
                    .build(true)
                    .toUri();

            ServerHttpRequest request = exchange.getRequest().mutate().uri(newUri).build();

            return chain.filter(exchange.mutate().request(request).build());
        }
    }

    @Override
    public int getOrder() {
        //在GatewayFilter之后执行
        return 10;
    }
}

 

3. GatewayFilter

 

@Component
public class IgnoreTestGlobalFilterFactor extends AbstractGatewayFilterFactory {

    public IgnoreTestGlobalFilterFactor() {
        super(Config.class);
    }

    @Override
    public GatewayFilter apply(Config config) {
        return this::filter;
    }

    public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        exchange.getAttributes().put(TestGlobalFilter.ATTRIBUTE_IGNORE_TEST_GLOBAL_FILTER, true);
        return chain.filter(exchange);
    }

    public static class Config {

    }

    @Override
    public String name() {
        return "IgnoreTestGlobalFilter";
    }
}

4. 配置路由

 

spring:
  cloud:
    gateway:
      routes:
      - id: gloabl_filter
        uri: http://localhost:4101
        predicates:
        - Path=/filter/**
        filters:
        - StripPrefix=1
      - id: no_filter
        uri: http://localhost:4101
        predicates:
        - Path=/no-filter/**
        filters:
        - StripPrefix=1
        - IgnoreTestGlobalFilter  #在本路由启用跳过全局过滤器

5. 效果

spring cloud gateway 某些路由中跳过全局过滤器_第1张图片

有过滤器

spring cloud gateway 某些路由中跳过全局过滤器_第2张图片

无过滤器



作者:giafei
链接:https://www.jianshu.com/p/42455cdc6d25
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

你可能感兴趣的:(springcloud)