Spring Cloud Gateway全局过滤器GlobalFilter初探

定义

在【spring cloud gateway】的官方文档中,全局过滤器GlobalFilter接口是这样定义的:

The GlobalFilter interface has the same signature as GatewayFilter. These are special filters that are conditionally applied to all routes. (This interface and usage are subject to change in future milestones).
  • GlobalFilter 和 GatewayFilter 的 #filter(ServerWebExchange, GatewayFilterChain) 方法签名一致;
  • GlobalFilter会作用于所有的路由上;
  • 在未来的里程碑版本中可能作一些调整;

org.springframework.cloud.gateway.filter.GlobalFilter,接口源代码:

public interface GlobalFilter {

    /**
     * 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} to indicate when request processing is complete
     */
    Mono filter(ServerWebExchange exchange, GatewayFilterChain chain);

}

GlobalFilter实现类

关于GlobalFilter接口内置的实现类主要有11个,均位于 org.springframework.cloud.gateway.filter 包中,如下:

IDEA查看类图快捷键

  • Ctrl + Alt + Shift + U:查看GlobalFilter类图;
  • Ctrl + T:查看GlobalFilter接口的所有实现类;

各个实现类的顺序如下( 数值越小,优先级越高,括号中为源码中的值 ):

  • AdaptCachedBodyGlobalFilter-2147482648 ( Ordered.HIGHEST_PRECEDENCE + 1000 )
  • ForwardPathFilter0
  • ForwardRoutingFilter2147483647 ( Ordered.LOWEST_PRECEDENCE )
  • GatewayMetricsFilter0
  • LoadBalancerClientFilter10100
  • NettyRoutingFilter2147483647 ( Ordered.LOWEST_PRECEDENCE )
  • NettyWriteResponseFilter-1
  • RouteToRequestUrlFilter10000
  • WebClientHttpRoutingFilter2147483647 ( Ordered.LOWEST_PRECEDENCE )
  • WebClientWriteResponseFilter-1
  • WebsocketRoutingFilter2147483646 ( Ordered.LOWEST_PRECEDENCE - 1 )

其中关于 org.springframework.core.Ordered 类源码如下:

package org.springframework.core;

public interface Ordered {
    int HIGHEST_PRECEDENCE = -2147483648;
    int LOWEST_PRECEDENCE = 2147483647;

    int getOrder();
}

GlobalFilter实现类实例化配置

各个GlobalFilter实现类具体实例化分别是在 org.springframework.cloud.gateway.config.GatewayAutoConfigurationorg.springframework.cloud.gateway.config.GatewayLoadBalancerClientAutoConfigurationorg.springframework.cloud.gateway.config.GatewayMetricsAutoConfiguration 中配置的,如下:

1、GatewayAutoConfiguration

在GatewayAutoConfiguration中配置的GlobalFilter实现类主要有

  • AdaptCachedBodyGlobalFilter
  • RouteToRequestUrlFilter
  • ForwardRoutingFilter
  • ForwardPathFilter
  • WebsocketRoutingFilter

在gateway-core 2.0.1版本中被注释掉的两个

  • WebClientHttpRoutingFilter
  • WebClientWriteResponseFilter

相关源代码如下:

    // GlobalFilter beans

    @Bean
    public AdaptCachedBodyGlobalFilter adaptCachedBodyGlobalFilter() {
        return new AdaptCachedBodyGlobalFilter();
    }

    @Bean
    public RouteToRequestUrlFilter routeToRequestUrlFilter() {
        return new RouteToRequestUrlFilter();
    }

    @Bean
    @ConditionalOnBean(DispatcherHandler.class)
    public ForwardRoutingFilter forwardRoutingFilter(DispatcherHandler dispatcherHandler) {
        return new ForwardRoutingFilter(dispatcherHandler);
    }

    @Bean
    public ForwardPathFilter forwardPathFilter() {
        return new ForwardPathFilter();
    }

    @Bean
    public WebSocketService webSocketService() {
        return new HandshakeWebSocketService();
    }

    @Bean
    public WebsocketRoutingFilter websocketRoutingFilter(WebSocketClient webSocketClient,
                                                         WebSocketService webSocketService,
                                                         ObjectProvider> headersFilters) {
        return new WebsocketRoutingFilter(webSocketClient, webSocketService, headersFilters);
    }

    @Bean
    public WeightCalculatorWebFilter weightCalculatorWebFilter(Validator validator) {
        return new WeightCalculatorWebFilter(validator);
    }

    /*@Bean
    //TODO: default over netty? configurable
    public WebClientHttpRoutingFilter webClientHttpRoutingFilter() {
        //TODO: WebClient bean
        return new WebClientHttpRoutingFilter(WebClient.routes().build());
    }

    @Bean
    public WebClientWriteResponseFilter webClientWriteResponseFilter() {
        return new WebClientWriteResponseFilter();
    }*/

2、GatewayAutoConfiguration.NettyConfiguration

在GatewayAutoConfiguration.NettyConfiguration中配置的GlobalFilter实现类主要有

  • NettyRoutingFilter
  • NettyWriteResponseFilter

相关源代码如下:

  @Bean
  public NettyRoutingFilter routingFilter(HttpClient httpClient,
                                          ObjectProvider> headersFilters,
                                          HttpClientProperties properties) {
      return new NettyRoutingFilter(httpClient, headersFilters, properties);
  }

  @Bean
  public NettyWriteResponseFilter nettyWriteResponseFilter(GatewayProperties properties) {
      return new NettyWriteResponseFilter(properties.getStreamingMediaTypes());
  }

3、GatewayLoadBalancerClientAutoConfiguration

在GatewayLoadBalancerClientAutoConfiguration中配置的GlobalFilter实现类主要有

  • LoadBalancerClientFilter

相关源代码如下:

@Configuration
@ConditionalOnClass({LoadBalancerClient.class, RibbonAutoConfiguration.class, DispatcherHandler.class})
@AutoConfigureAfter(RibbonAutoConfiguration.class)
public class GatewayLoadBalancerClientAutoConfiguration {

    // GlobalFilter beans

    @Bean
    @ConditionalOnBean(LoadBalancerClient.class)
    public LoadBalancerClientFilter loadBalancerClientFilter(LoadBalancerClient client) {
        return new LoadBalancerClientFilter(client);
    }
}

4、GatewayMetricsAutoConfiguration

在GatewayMetricsAutoConfiguration中配置的GlobalFilter实现类主要有

  • GatewayMetricsFilter

相关源代码如下:

@Configuration
@ConditionalOnProperty(name = "spring.cloud.gateway.enabled", matchIfMissing = true)
@AutoConfigureBefore(HttpHandlerAutoConfiguration.class)
@AutoConfigureAfter({ MetricsAutoConfiguration.class,
        CompositeMeterRegistryAutoConfiguration.class })
@ConditionalOnClass({ DispatcherHandler.class, MeterRegistry.class, MetricsAutoConfiguration.class})
public class GatewayMetricsAutoConfiguration {
    @Bean
    @ConditionalOnBean(MeterRegistry.class)
    @ConditionalOnProperty(name = "spring.cloud.gateway.metrics.enabled", matchIfMissing = true)
    public GatewayMetricsFilter gatewayMetricFilter(MeterRegistry meterRegistry) {
        return new GatewayMetricsFilter(meterRegistry);
    }
}

通过内置监控端点查看实际实例化的GlobalFilter实现类

1、首先引入actuator模块,添加如下依赖


    org.springframework.boot
    spring-boot-starter-actuator

2、在配置文件application.yml中开启监控管理端点

management:
  endpoint:
    gateway:
      enabled: true
  endpoints:
    web:
      exposure:
        include: "*"

如果不进行如上配置,默认情况下只会看到下面的三个路由:

  • /actuator/health
  • /actuator/info
  • /actuator

配置之后,就可以看到有关 GlobalFilter 的端点路由信息:

  • /actuator/gateway/globalfilters

3、在浏览器中访问 http://localhost:8080/actuator/gateway/globalfilters,返回如下信息

{
    "org.springframework.cloud.gateway.filter.NettyWriteResponseFilter@499ef98e":-1,
    "org.springframework.cloud.gateway.filter.AdaptCachedBodyGlobalFilter@24934262":-2147482648,
    "org.springframework.cloud.gateway.filter.GatewayMetricsFilter@5b051a5c":0,
    "org.springframework.cloud.gateway.filter.ForwardRoutingFilter@288214b1":2147483647,
    "org.springframework.cloud.gateway.filter.ForwardPathFilter@16eedaa6":0,
    "org.springframework.cloud.gateway.filter.NettyRoutingFilter@5fcfca62":2147483647,
    "org.springframework.cloud.gateway.filter.RouteToRequestUrlFilter@93f432e":10000,
    "org.springframework.cloud.gateway.filter.WebsocketRoutingFilter@28501a4b":2147483646
}

从这里可以看到,如果只引入 spring-cloud-starter-gateway 依赖的情况下,默认只会实例化 8个 GlobalFilter实现类,并非 11个,这是因为有些GlobalFilter实现类的实例化是需要一定依赖条件的,比如 LoadBalancerClientFilter ,它的依赖类是 LoadBalancerClient.class,源码:

@Bean
@ConditionalOnBean(LoadBalancerClient.class)
public LoadBalancerClientFilter loadBalancerClientFilter(LoadBalancerClient client) {
  return new LoadBalancerClientFilter(client);
}

还有另外2个默认情况也是没有实例化的,分别是 WebClientHttpRoutingFilterWebClientWriteResponseFilter,因为这两个实例化配置在源码中被注释掉了,上文有提到过。

总结

这篇文章只是简单地探索了一下Spring Cloud Gateway的GlobalFilter及其默认的实现类,并未涉及到具体过滤器的作用,后续文章再一一作补充

参考

【Spring Cloud Gateway官方文档】
【Spring Cloud Gateway源代码】

你可能感兴趣的:(spring-cloud,gateway)