GateWay过滤器执行顺序源码分析

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()
    defaultFilterroute的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);
}

总结:

  1. order越小过滤器越靠前
  2. order一样时,defaultFilter > 路由过滤器 > GlobalFilter
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值