Spring Cloud Gateway全局过滤器GlobalFilter初探

news/2024/7/5 21:15:12

定义

在【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<Void>} to indicate when request processing is complete
     */
    Mono<Void> 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<List<HttpHeadersFilter>> 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<List<HttpHeadersFilter>> 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模块,添加如下依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

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源代码】


http://www.niftyadmin.cn/n/4261155.html

相关文章

主引导分区VS超级块

硬盘里分为两个区域,一个是实际文件数据文件放置的地方,一个是放置关于整个硬盘的信息区,我们称这个为主引导分区(MBR,MASTER BOOT RECORDER)。MBR里记录了两个重要的信息&#xff0c;分别是&#xff1a;引导程序与磁盘分区表。由于MBR仅能保存4个分区的数据记录&#xff0c;如…

mysql数据库在什么程序操作_MYSQL数据库基本操作

一&#xff0c;MYSQL数据库的简介1&#xff0c;数据库的概念数据库就是以一定格式进行组织的数据的集合。通俗来看数据库就是用户计算机上 一些具有特殊格式的数据文件的集合。2&#xff0c;相比于普通文件&#xff0c;数据库的特点1)持久化存储&#xff0c;2)读写速度极高&…

FreeBSD内核编译注意事项[zt]

http://hi.baidu.com/iamacnhero/blog/item/54c272032cab60ef08fa935f.html在核心设定中加入 options QUOTA 这一行&#xff0c;启用磁盘配额。使核心支持 NAT 及防火墙功能&#xff1a;# 防火墙options IPFIREWALL# 支援 NAToptions IPDIVERT# 下面这一行是预设允许所有封包通…

我发起了一个 支持 PostgreSql 的 外围设施 的 .Net 开源项目

目标 &#xff1a; 让 PostgreSql 成为 通用的 跨平台 的 数据库 &#xff0c; 成为 开发者 喜爱 的 利器 。 要做的事 &#xff0c; 当然 &#xff0c; PostgreSql 本身现在不用我们去做什么 。 一个 数据库 要成为 开发者喜爱的 流行的 普遍使用的 数据库 &#xff0c; 需要…

c# mysql 参数使用实例_C#操作MySQL数据库的简单例子

本示例演示了用C#操作MySQL的方法&#xff0c;提供了三个可重用的类MySqlDBUtil,MySqlPageUtil,Page。本示例由 C#操作Access数据库的简单例子修改而来。1.首先下载MySQL数据库的.NET驱动http://dev.mysql.com/get/Downloads/Connector-Net/mysql-connector-net-5.0.8.1-noinst…

How To Determinate If An EMCPOWER Partition Is Valid For ASMLIB

If you are trying to create an ASMLIB disk using an emcpower# partition and you get the next error: ASMdisk:asmtool:Device"/dev/emcpowera11"isnotapartition[FAILED] Then you will need to determinate if the emcpower# partition is valid. 解决步骤如下…

终于开博了,庆祝下。

我是个懒人&#xff0c;不喜欢写日记。高中三年一个日记本好不容易记了大半本&#xff0c;大学到现在研二了&#xff0c;已经快6年了&#xff0c;一个日记本也才用了一半&#xff0c;对我而言&#xff0c;这已经不是纯粹的日记了。已经是月记年记了。只是在心情不好时&#xff…

smarty mysql demo_smarty模板的使用方法实例分析

本文实例讲述了smarty模板的使用方法。分享给大家供大家参考&#xff0c;具体如下&#xff1a;这里以smarty3为例首先&#xff0c; 在官网下载smarty3模板文件&#xff0c;然后解压。在解压之后的文件夹中&#xff0c;libs是smarty模板的核心文件&#xff0c;demo里面有示例程序…