SpringCloud Gateway中Filters详细说明

前面 https://blog.csdn.net/J080624/article/details/139494909 我们研究了GateWay中各种路由断言的使用。SpringCloud GateWay 还提供了各种过滤器用来对请求和响应进行处理。

官网地址:SpringCloud Gateway Filter

【1】GatewayFilter Factories

路由过滤器允许对请求和响应进行修改。路由过滤器只作用于特定路由,如果想某些规则应用于所有路由,那么需要使用 spring.cloud.gateway.default-filters.

Spring Cloud Gateway包含了许多内置GatewayFilter Factories。

如图所示这里有31个过滤器,这里只捡几个说明,感兴趣的可以查看官方文档

① AddRequestHeader GatewayFilter Factory

为指定路由添加请求头,需要两个参数:请求头名称和值。值格式同样支持URI variables 。

yaml 复制代码
spring:
  cloud:
    gateway:
      routes:
      - id: add_request_header_route
        uri: https://example.org
        filters:
        - AddRequestHeader=X-Request-red, blue

② AddRequestParameter GatewayFilter Factory

为指定路由匹配的所有请求添加请求参数。需要两个参数:请求参数名称和值。值格式同样支持URI variables 。

yaml 复制代码
spring:
  cloud:
    gateway:
      routes:
      - id: add_request_parameter_route
        uri: https://example.org
        filters:
        - AddRequestParameter=red, blue

③ AddResponseHeader GatewayFilter Factory

为指定路由匹配的所有请求添加响应头。需要两个参数:响应头名称和值。值格式同样支持URI variables 。

yaml 复制代码
spring:
  cloud:
    gateway:
      routes:
      - id: add_response_header_route
        uri: https://example.org
        filters:
        - AddResponseHeader=X-Response-Red, Blue

④ DedupeResponseHeader GatewayFilter Factory

Dedupe是重复数据消除的意思,也就是消除指定的请求头重复数据。

yaml 复制代码
spring:
  cloud:
    gateway:
      routes:
      - id: dedupe_response_header_route
        uri: https://example.org
        filters:
        - DedupeResponseHeader=Access-Control-Allow-Credentials Access-Control-Allow-Origin

上面将会消除Access-Control-Allow-Credentials和Access-Control-Allow-Origin的重复值。

⑨ PrefixPath GatewayFilter Factory

添加统一的请求前缀。

yaml 复制代码
spring:
  cloud:
    gateway:
      routes:
      - id: prefixpath_route
        uri: https://example.org
        filters:
        - PrefixPath=/mypath

将会为匹配的所有请求添加前缀 /mypath,假设请求为/hello 将会变为 /mypath/hello

【2】Global Filters

SpringCloud Gateway同样内置了一些全局过滤器GlobalFilter ,GlobalFilter接口具有与GatewayFilter相同的特征。这些是有条件地应用于所有路由的特殊过滤器。

① Forward Routing Filter

从ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR获取uri,如果这个uri有一个 forward 协议比如forward:///localendpoint。那么就会使用Spring的DispatcherHandler 进行处理。

The path part of the request URL is overridden with the path in the forward URL. The unmodified original URL is appended to the list in the ServerWebExchangeUtils.GATEWAY_ORIGINAL_REQUEST_URL_ATTR attribute.

核心处理逻辑如下:

java 复制代码
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
      URI requestUrl = (URI)exchange.getRequiredAttribute(ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR);
      String scheme = requestUrl.getScheme();
      if (!ServerWebExchangeUtils.isAlreadyRouted(exchange) && "forward".equals(scheme)) {
          if (log.isTraceEnabled()) {
              log.trace("Forwarding to URI: " + requestUrl);
          }

          return this.getDispatcherHandler().handle(exchange);
      } else {
          return chain.filter(exchange);
      }
  }

② LoadBalancerClient Filter

LoadBalancerClientFilter 会从 ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR获取uri,如果这个uri有一个 lb 协议比如lb://myservice,它使用Spring Cloud LoadBalancerClient将服务名称(在本例中为myservice)解析为实际的主机和端口,并替换同一属性中的URI。

未被修改的原始URL将会追加到ServerWebExchangeUtils.GATEWAY_ORIGINAL_REQUEST_URL_ATTR中。

这个过滤器同样从ServerWebExchangeUtils.GATEWAY_SCHEME_PREFIX_ATTR寻找并判断是否有值等于lb,如果是,同样适用于该规则。下述实例配置了一个LoadBalancerClientFilter:

yaml 复制代码
spring:
  cloud:
    gateway:
      routes:
      - id: myRoute
        uri: lb://service
        predicates:
        - Path=/service/**

默认情况下如果服务实例在LoadBalancer找不到,那么将会返回503。你可以通过配置将其修改为404.

yaml 复制代码
spring.cloud.gateway.loadbalancer.use404=true

【3】自定义全局过滤器

上面都是Gateway给我们提供的各种Filter,实际业务中我们往往是通过实现GlobalFilter接口达到我们预期目标。

参考博文:SpringCloud Gateway使用过滤器对IP和接口进行策略限制

相关推荐
JHC00000016 小时前
dy直播间评论保存插件
java·后端·python·spring cloud·信息可视化
华大哥17 小时前
spring cloud微服务实战:consul+Feign/Ribbon服务注册和远程调用
spring cloud·微服务·ribbon·consul·java-consul
黄俊懿1 天前
【深入理解SpringCloud微服务】Seata(AT模式)源码解析——全局事务的提交
java·后端·spring·spring cloud·微服务·架构·架构师
骚戴1 天前
n1n:从替代LiteLLM Proxy自建网关到企业级统一架构的进阶之路
人工智能·python·大模型·llm·gateway·api
墨痕诉清风2 天前
java漏洞集合工具(Struts2、Fastjson、Weblogic(xml)、Shiro、Log4j、Jboss、SpringCloud)
xml·java·struts·安全·web安全·spring cloud·log4j
⑩-2 天前
SpringCloud-Feign客户端实战
后端·spring·spring cloud
楠枬2 天前
Nacos
java·spring·spring cloud·微服务
骚戴2 天前
LLM API Gateway:LLM API 架构、AI 聚合与成本优化全解(2025深度指南)
人工智能·python·大模型·llm·gateway·api
一人の梅雨2 天前
京东商品详情接口深度解析:从宙斯签名到商详数据价值重构
java·spring cloud·微服务
Dolphin_Home2 天前
从理论到实战:图结构在仓库关联业务中的落地(小白→中级,附完整代码)
java·spring boot·后端·spring cloud·database·广度优先·图搜索算法