/**
* 网关过滤链表接口
* 用于过滤器的链式调用
* contract to allow a {@link webfilter} to delegate to the next in the chain.
*
* @author rossen stoyanchev
* @since 5.0
*/
public interface gatewayfilterchain {
/**
* 链表启动调用入口方法
* delegate to the next {@code webfilter} in the chain.
* @param exchange the current server exchange
* @return {@code mono<void>} to indicate when request handling is complete
*/
mono<void> filter(serverwebexchange exchange);
}
/**
* 网关过滤的链表,用于过滤器的链式调用
* 过滤器链表接口的默认实现,
* 包含2个构建函数:
* 1.集合参数构建用于初始化吧构建链表
* 2. index,parent参数用于构建当前执行过滤对应的下次执行的链表
*/
private static class defaultgatewayfilterchain implements gatewayfilterchain {
/**
* 当前过滤执行过滤器在集合中索引
*/
private final int index;
/**
* 过滤器集合
*/
private final list<gatewayfilter> filters;
public defaultgatewayfilterchain(list<gatewayfilter> filters) {
this.filters = filters;
this.index = 0;
}
/**
* 构建
* @param parent 上一个执行过滤器对应的filterchain
* @param index 当前要执行过滤器的索引
*/
private defaultgatewayfilterchain(defaultgatewayfilterchain parent, int index) {
this.filters = parent.getfilters();
this.index = index;
}
public list<gatewayfilter> getfilters() {
return filters;
}
/**
* @param exchange the current server exchange
* @return
*/
@override
public mono<void> filter(serverwebexchange exchange) {
return mono.defer(() -> {
if (this.index < filters.size()) {
//获取当前索引的过滤器
gatewayfilter filter = filters.get(this.index);
//构建当前索引的下一个过滤器的filterchain
defaultgatewayfilterchain chain = new defaultgatewayfilterchain(this, this.index + 1);
//调用过滤器的filter方法执行过滤器
return filter.filter(exchange, chain);
} else {
//当前索引大于等于过滤集合大小,标识所有链表都已执行完毕,返回空
return mono.empty(); // complete
}
});
}
}
/**
* 网关路由过滤器,
* contract for interception-style, chained processing of web requests that may
* be used to implement cross-cutting, application-agnostic requirements such
* as security, timeouts, and others. specific to a gateway
*
* copied from webfilter
*
* @author rossen stoyanchev
* @since 5.0
*/
public interface gatewayfilter extends shortcutconfigurable {
string name_key = "name";
string value_key = "value";
/**
* 过滤器执行方法
* process the web request and (optionally) delegate to the next
* {@code webfilter} through the given {@link gatewayfilterchain}.
* @param exchange the current server exchange
* @param chain provides a way to delegate to the next filter
* @return {@code mono<void>} to indicate when request processing is complete
*/
mono<void> filter(serverwebexchange exchange, gatewayfilterchain chain);
}