在项目中有个特殊的模块,可走可不走gateway,如果让他走gateway,可以定义一个忽略全局过滤器判断的过滤器。

定义IgnoreGlobalFilter

  1. @Component
  2. public class IgnoreGlobalFilterFactor extends AbstractGatewayFilterFactory<IgnoreGlobalFilterFactor.Config> {
  3. public IgnoreGlobalFilterFactor() {
  4. super(Config.class);
  5. }
  6. @Override
  7. public GatewayFilter apply(Config config) {
  8. return this::filter;
  9. }
  10. public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
  11. exchange.getAttributes().put("@ignoreTestGlobalFilter", true);
  12. return chain.filter(exchange);
  13. }
  14. public static class Config {
  15. }
  16. @Override
  17. public String name() {
  18. return "IgnoreGlobalFilter";
  19. }
  20. }

在全局GlobalFilter中判断忽略@ignoreTestGlobalFilter属性

  1. public final static String ATTRIBUTE_IGNORE_GLOBAL_FILTER = "@ignoreTestGlobalFilter";
  2. @Override
  3. public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
  4. // 跳过检测
  5. if (exchange.getAttribute(ATTRIBUTE_IGNORE_GLOBAL_FILTER) != null) {
  6. return chain.filter(exchange);
  7. }

配置启用IgnoreGlobalFilter

  1. spring:
  2. cloud:
  3. gateway:
  4. routes:
  5. - id: gloabl_filter
  6. uri: http://localhost:4101
  7. predicates:
  8. - Path=/filter/**
  9. filters:
  10. - StripPrefix=1
  11. - id: no_filter
  12. uri: http://localhost:4101
  13. predicates:
  14. - Path=/no-filter/**
  15. filters:
  16. - StripPrefix=1
  17. - IgnoreGlobalFilter #在本路由启用跳过全局过滤器