在Spring Cloud Gateway中GlobalFilter可以方便的全局?jǐn)r截或統(tǒng)計久信,有時候希望在某些路由中可以跳過GlobalFilter留凭,可以通過GatewayFilter與GlobalFilter組合來實現(xiàn)。
1. 新建項目
新建一個 Spring Cloud Gateway的項目明郭,添加對應(yīng)的依賴
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 {
//簡單增加一個參數(shù)
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之后執(zhí)行
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 #在本路由啟用跳過全局過濾器