美文网首页
spring cloud gateway 某些路由中跳过全局过滤

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

作者: giafei | 来源:发表于2018-07-21 09:53 被阅读0次

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

1. 新建项目

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

2. GlobalFilter

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

    @Override
    public Mono<Void> 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<IgnoreTestGlobalFilterFactor.Config> {

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

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

    public Mono<Void> 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 某些路由中跳过全局过滤

      本文链接:https://www.haomeiwen.com/subject/vxwcmftx.html