提问者:小点点

Spring Cloud Gateway中的过滤器是否有推荐的订单范围?


我想知道Spring Cloud Gateway中是否有网关过滤器(全局或非全局)的推荐顺序范围,因为网关链中存在订单小于1且大于9999的Spring Gateway过滤器。请参阅:

{OrderedGatewayFilter@20770} "[GatewayFilterAdapter{delegate=org.springframework.cloud.gateway.filter.RemoveCachedBodyFilter@5eb974}, order = -2147483648]"
{OrderedGatewayFilter@20771} "[GatewayFilterAdapter{delegate=org.springframework.cloud.gateway.filter.AdaptCachedBodyGlobalFilter@ae5eeee}, order = -2147482648]"
{OrderedGatewayFilter@20772} "[GatewayFilterAdapter{delegate=org.springframework.cloud.gateway.filter.NettyWriteResponseFilter@492c1b1b}, order = -1]"
{OrderedGatewayFilter@20774} "[GatewayFilterAdapter{delegate=org.springframework.cloud.gateway.filter.ForwardPathFilter@3927de0e}, order = 0]"
{OrderedGatewayFilter@20775} "[GatewayFilterAdapter{delegate=org.springframework.cloud.gateway.filter.GatewayMetricsFilter@36dab184}, order = 0]"

// my custom filters should be here

{OrderedGatewayFilter@20791} "[GatewayFilterAdapter{delegate=org.springframework.cloud.gateway.filter.RouteToRequestUrlFilter@72f112d1}, order = 10000]"
{OrderedGatewayFilter@20792} "[GatewayFilterAdapter{delegate=org.springframework.cloud.gateway.config.GatewayNoLoadBalancerClientAutoConfiguration$NoLoadBalancerClientFilter@71b9b035}, order = 10150]"
{OrderedGatewayFilter@20793} "[GatewayFilterAdapter{delegate=org.springframework.cloud.gateway.filter.WebsocketRoutingFilter@4c475547}, order = 2147483646]"
{OrderedGatewayFilter@20794} "[GatewayFilterAdapter{delegate=org.springframework.cloud.gateway.filter.NettyRoutingFilter@189f5ed8}, order = 2147483647]"
{OrderedGatewayFilter@20795} "[GatewayFilterAdapter{delegate=org.springframework.cloud.gateway.filter.ForwardRoutingFilter@10faebc9}, order = 2147483647]"

我的自定义全局过滤器实现了有序接口:

@Component
public class GlobalFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { ... }
 
    @Override
    public int getOrder() {
        return 2; // here
    }
}

我的网关过滤器是OrderedGatewayFilter:

@Component
public class CustomFilter implements GatewayFilterFactory<CustomFilter.Config> {

    @Override
    public GatewayFilter apply(Config config) {
        return new OrderedGatewayFilter((exchange, chain) -> {
           ...
        }, 3); // here
    }

   ...
}

我的过滤器应该在1…9999范围内吗?或者将我的自定义过滤器放在这些Spring Cloud Gateway过滤器之前或之后没有问题吗?


共1个答案

匿名用户

筛选链按照org. springframe.core.Or的接口排序。根据Spring Framework留档上的注解类型顺序:

缺省值为有序。LOWEST_PRECEDENCE,表示最低优先级(丢失到任何其他指定的顺序值)。

但是

较低的值具有较高的优先级。

如果在IDE中检查,则可能的最低值(优先级最高)为-2147483648。可能的最高值为2147483647。

从全局过滤器的留档和一些经验来看,-1是一个起点,你可以安排你需要的顺序。或者,如果你有一个过滤器总是需要先执行,请使用有序。HIGHEST_PRECEDENCE并从那里订购其他过滤器,如有序。HIGHEST_PRECEDENCE1等。

编辑:Spring Cloud Gateway内部有一些硬编码的Filter Orders,例如NettyWriteResponse seFilter中的"WRITE_RESPONSE_FILTER_ORDER=-1"。如果您担心干扰,请检查源代码进行排序。