我想知道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过滤器之前或之后放置我的自定义过滤器没有问题吗?
过滤链按照org.springframework.core.Ordered接口进行排序。根据Spring Framework关于注释类型顺序的文档:
默认值为Ordered.LOWEST_PRECDENCE,表示最低优先级(丢失到任何其他指定的顺序值(。
但是
值越低,优先级越高。
如果在IDE中进行检查,则可能的最低值(具有最高优先级(为-2147483648。最大可能值为2147483647。
从关于全局过滤器的文档和一些经验来看,-1是一个起点,您可以围绕它安排所需的订单。或者,如果您有一个过滤器总是需要首先执行,请使用Ordered.HIGHTEST_PRECEDENSE并从中排序其他过滤器,如Ordered.HigHTEST_PreceEDENSE+1等。
编辑:Spring Cloud Gateway内部有一些硬编码的Filter Order,例如";WRITE_ RESPONSE_;在NettyWriteResponseFilter中。如果您担心干扰,请查看源代码以进行订购。