在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 #在本路由启用跳过全局过滤器
网友评论