Spring Cloud Gateway 源码剖析之Filter Chain过滤器链
public class DefaultGatewayFilterChain implements GatewayFilterChain {
private final List<GatewayFilter> gatewayFilters;
private final ServerWebExchange exchange;
private int currentFilterIndex = 0;
public DefaultGatewayFilterChain(List<GatewayFilter> gatewayFilters, ServerWebExchange exchange) {
this.gatewayFilters = gatewayFilters;
this.exchange = exchange;
}
@Override
public Mono<Void> filter() {
if (currentFilterIndex >= gatewayFilters.size()) {
return Mono.empty(); // 没有更多的过滤器,返回一个空的Mono
}
GatewayFilter filter = gatewayFilters.get(currentFilterIndex++); // 获取当前过滤器并递增索引
return filter.filter(exchange, this); // 使用当前过滤器并递归调用filter方法进入下一个过滤器
}
}
这个代码示例展示了如何实现一个默认的Spring Cloud Gateway过滤器链。它使用了ServerWebExchange
来传递请求和响应,并维护了当前过滤器的索引以便逐个应用列表中的过滤器。通过递归调用过滤器链的filter
方法,每个请求都会依次经过所有配置的过滤器。
评论已关闭