GateWay过滤器执行顺序源码分析
- AddRequestHeaderGatewayFilterFactory
配置文件中配有AddRequestHeader就会执行apply方法返回GatewayFilter
public class AddRequestHeaderGatewayFilterFactory
extends AbstractNameValueGatewayFilterFactory {
@Override
public GatewayFilter apply(NameValueConfig config) {
return new GatewayFilter() {
@Override
public Mono<Void> filter(ServerWebExchange exchange,
GatewayFilterChain chain) {
String value = ServerWebExchangeUtils
.expand(exchange, config.getValue());
ServerHttpRequest request = exchange.getRequest().mutate()
.header(config.getName(), value).build();
return chain.filter(exchange.mutate().request(request).build());
}
};
}
}
- FilteringWebHandler.GatewayFilterAdapter
将GlobalFilter
->GateWayFilter
,这样就可以把这两个类合并在一起操作了
private static class GatewayFilterAdapter implements GatewayFilter {
private final GlobalFilter delegate;
GatewayFilterAdapter(GlobalFilter delegate) {
this.delegate = delegate;
}
}
- RouteDefinitionRouteLocator#getRoutes()
先加载defaultFilter,再加载route的filter,然后合并
private List<GatewayFilter> getFilters(RouteDefinition routeDefinition) {
List<GatewayFilter> filters = new ArrayList<>();
// 如果默认过滤器不为空就加入filters过滤器链中
if (!this.gatewayProperties.getDefaultFilters().isEmpty()) {
filters.addAll(loadGatewayFilters(DEFAULT_FILTERS,
new ArrayList<>(this.gatewayProperties.getDefaultFilters())));
}
// 如果route的过滤器不为空就加入filters过滤器链中
if (!routeDefinition.getFilters().isEmpty()) {
filters.addAll(loadGatewayFilters(routeDefinition.getId(), // route的id
new ArrayList<>(routeDefinition.getFilters())));
}
// 给filters链进行排序并返回
AnnotationAwareOrderComparator.sort(filters);
return filters;
}
- FilteringWebHandler#handle()
将defaultFilter
和route的filter
以及全局过滤器
合并 + 排序
@Override
public Mono<Void> handle(ServerWebExchange exchange) {
// 获取defaultFilter和route filter
Route route = exchange.getRequiredAttribute(GATEWAY_ROUTE_ATTR);
List<GatewayFilter> gatewayFilters = route.getFilters();
// 获取全局过滤器 -> 转成GatewayFilter
List<GatewayFilter> combined = new ArrayList<>(this.globalFilters);
combined.addAll(gatewayFilters); // 合并操作
AnnotationAwareOrderComparator.sort(combined); // 排序
if (logger.isDebugEnabled()) {
logger.debug("Sorted gatewayFilterFactories: " + combined);
}
return new DefaultGatewayFilterChain(combined).filter(exchange);
}
总结:
- order越小过滤器越靠前
- order一样时,
defaultFilter
>路由过滤器
>GlobalFilter