在项目中有个特殊的模块,可走可不走gateway,如果让他走gateway,可以定义一个忽略全局过滤器判断的过滤器。
定义IgnoreGlobalFilter
@Component
public class IgnoreGlobalFilterFactor extends AbstractGatewayFilterFactory<IgnoreGlobalFilterFactor.Config> {
public IgnoreGlobalFilterFactor() {
super(Config.class);
}
@Override
public GatewayFilter apply(Config config) {
return this::filter;
}
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
exchange.getAttributes().put("@ignoreTestGlobalFilter", true);
return chain.filter(exchange);
}
public static class Config {
}
@Override
public String name() {
return "IgnoreGlobalFilter";
}
}
在全局GlobalFilter中判断忽略@ignoreTestGlobalFilter属性
public final static String ATTRIBUTE_IGNORE_GLOBAL_FILTER = "@ignoreTestGlobalFilter";
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
// 跳过检测
if (exchange.getAttribute(ATTRIBUTE_IGNORE_GLOBAL_FILTER) != null) {
return chain.filter(exchange);
}
配置启用IgnoreGlobalFilter
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
- IgnoreGlobalFilter #在本路由启用跳过全局过滤器