GatewayFilter 工厂

"
"

路由过滤器允许以某种方式修改传入的 HTTP 请求或传出的 HTTP 响应。路由过滤器仅针对特定的路由进行配置。Spring Cloud Gateway 包含许多内置的 GatewayFilter 工厂。

路由过滤器允许以某种方式修改传入的 HTTP 请求或传出的 HTTP 响应。路由过滤器仅针对特定的路由进行配置。Spring Cloud Gateway 包含许多内置的 GatewayFilter 工厂。

注意

对于以下过滤器的使用方法,可以查看单元测试中的更多详细示例。

AddRequestHeader GatewayFilter 工厂

AddRequestHeader GatewayFilter 工厂 需要 namevalue 两个参数。下面的例子展示了如何配置一个 AddRequestHeader GatewayFilter

application.yml
                        spring:
  cloud:
    gateway:
      routes:
      - id: add_request_header_route
        uri: https://example.org
        filters:
        - AddRequestHeader=X-Request-red, blue

                    
yaml

对于所有匹配的请求,这个配置会在下游请求的 headers 中添加 X-Request-red:blue

AddRequestHeader 能够识别用于匹配路径或主机的 URI 变量。URI 变量可以在 value 中使用,并在运行时展开。

application.yml
                        spring:
  cloud:
    gateway:
      routes:
      - id: add_request_header_route
        uri: https://example.org
        predicates:
        - Path=/red/{segment}
        filters:
        - AddRequestHeader=X-Request-Red, Blue-{segment}

                    
yaml

AddRequestHeadersIfNotPresent GatewayFilter 工厂

AddRequestHeadersIfNotPresent GatewayFilter 工厂接受一组由冒号分隔的 namevalue 键值对。下面的例子展示了如何配置一个 AddRequestHeadersIfNotPresent GatewayFilter:

application.yml
                        spring:
  cloud:
    gateway:
      routes:
      - id: add_request_headers_route
        uri: https://example.org
        filters:
        - AddRequestHeadersIfNotPresent=X-Request-Color-1:blue,X-Request-Color-2:green

                    
yaml

这个配置会为所有匹配的请求添加两个 header:X-Request-Color-1:blueX-Request-Color-2:green 到下游请求的 headers 中。这与 AddRequestHeader 的工作方式类似,但不同的是,它只会在 header 不存在的情况下添加。如果 header 已存在,则会保留客户端请求中的原始值。

另外,要设置多值 header,可以多次使用相同的 header 名称,如 AddRequestHeadersIfNotPresent=X-Request-Color-1:blue,X-Request-Color-1:green

AddRequestHeadersIfNotPresent 同样支持用于匹配路径或主机的 URI 变量。URI 变量可以在 value 中使用,并在运行时展开。下面的例子配置了一个使用变量的 AddRequestHeadersIfNotPresent GatewayFilter:

application.yml
                        spring:
  cloud:
    gateway:
      routes:
      - id: add_request_header_route
        uri: https://example.org
        predicates:
        - Path=/red/{segment}
        filters:
        - AddRequestHeadersIfNotPresent=X-Request-Red:Blue-{segment}

                    
yaml

AddRequestParameter GatewayFilter 工厂

AddRequestParameter GatewayFilter 工厂需要 namevalue 两个参数。下面的例子展示了如何配置一个 AddRequestParameter GatewayFilter:

application.yml
                        spring:
  cloud:
    gateway:
      routes:
      - id: add_request_parameter_route
        uri: https://example.org
        filters:
        - AddRequestParameter=red, blue

                    
yaml

这个配置会为所有匹配的请求在下游请求的查询字符串中添加 red=blue

AddRequestParameter 能够识别用于匹配路径或主机的 URI 变量。URI 变量可以在 value 中使用,并在运行时展开。下面的例子配置了一个使用变量的 AddRequestParameter GatewayFilter:

application.yml
                        spring:
  cloud:
    gateway:
      routes:
      - id: add_request_parameter_route
        uri: https://example.org
        predicates:
        - Host: {segment}.myhost.org
        filters:
        - AddRequestParameter=foo, bar-{segment}

                    
yaml

AddResponseHeader GatewayFilter 工厂

AddResponseHeader GatewayFilter 工厂需要 namevalue 两个参数。下面的例子展示了如何配置一个 AddResponseHeader GatewayFilter:

application.yml
                        spring:
  cloud:
    gateway:
      routes:
      - id: add_response_header_route
        uri: https://example.org
        filters:
        - AddResponseHeader=X-Response-Red, Blue

                    
yaml

这个配置会为所有匹配的请求在下游响应的 headers 中添加 X-Response-Red:Blue

AddResponseHeader 能够识别用于匹配路径或主机的 URI 变量。URI 变量可以在 value 中使用,并在运行时展开。下面的例子配置了一个使用变量的 AddResponseHeader GatewayFilter:

application.yml
                        spring:
  cloud:
    gateway:
      routes:
      - id: add_response_header_route
        uri: https://example.org
        predicates:
        - Host: {segment}.myhost.org
        filters:
        - AddResponseHeader=foo, bar-{segment}

                    
yaml

CircuitBreaker GatewayFilter 工厂

Spring Cloud CircuitBreaker GatewayFilter 工厂使用 Spring Cloud CircuitBreaker API 来为网关路由提供断路器功能。Spring Cloud CircuitBreaker 支持多个可以与 Spring Cloud Gateway 一起使用的库。Spring Cloud 默认支持 Resilience4J。

要启用 Spring Cloud CircuitBreaker 过滤器,你需要在 classpath 中添加 spring-cloud-starter-circuitbreaker-reactor-resilience4j 依赖。下面的例子配置了一个 Spring Cloud CircuitBreaker GatewayFilter:

application.yml
                        spring:
  cloud:
    gateway:
      routes:
      - id: circuitbreaker_route
        uri: https://example.org
        filters:
        - CircuitBreaker=myCircuitBreaker

                    
yaml

要配置断路器,请参考你使用的底层断路器实现的配置文档:

Spring Cloud CircuitBreaker 过滤器还可以接受一个可选的 fallbackUri 参数。目前只支持 forward: 模式的 URI。当触发 fallback 时,请求会被转发到与该 URI 匹配的控制器。下面的例子配置了这样的 fallback:

application.yml
                        spring:
  cloud:
    gateway:
      routes:
      - id: circuitbreaker_route
        uri: lb://backing-service:8088
        predicates:
        - Path=/consumingServiceEndpoint
        filters:
        - name: CircuitBreaker
          args:
            name: myCircuitBreaker
            fallbackUri: forward:/inCaseOfFailureUseThis
        - RewritePath=/consumingServiceEndpoint, /backingServiceEndpoint

                    
yaml

下面是使用 Java 代码实现相同功能的示例:

Application.java
                        @Bean
public RouteLocator routes(RouteLocatorBuilder builder) {
    return builder.routes()
        .route("circuitbreaker_route", r -> r.path("/consumingServiceEndpoint")
            .filters(f -> f.circuitBreaker(c -> c.name("myCircuitBreaker").fallbackUri("forward:/inCaseOfFailureUseThis"))
                .rewritePath("/consumingServiceEndpoint", "/backingServiceEndpoint")).uri("lb://backing-service:8088")
        .build();
}

                    
java

这个例子在断路器 fallback 被调用时会转发到 /inCaseofFailureUseThis URI。注意,这个例子同时演示了可选的 Spring Cloud LoadBalancer 负载均衡(通过目标 URI 上的 lb 前缀定义)。

CircuitBreaker 还支持在 fallbackUri 中使用 URI 变量。这允许更复杂的路由选项,比如使用 PathPattern 表达式转发原始主机或 URL 路径的部分内容。

在下面的例子中,对 consumingServiceEndpoint/users/1 的调用将被重定向到 inCaseOfFailureUseThis/users/1

application.yml
                        spring:
  cloud:
    gateway:
      routes:
      - id: circuitbreaker_route
        uri: lb://backing-service:8088
        predicates:
        - Path=/consumingServiceEndpoint/{*segments}
        filters:
        - name: CircuitBreaker
          args:
            name: myCircuitBreaker
            fallbackUri: forward:/inCaseOfFailureUseThis/{segments}

                    
yaml

主要场景是使用 fallbackUri 来定义网关应用程序内部的控制器或处理器。但是,你也可以将请求重新路由到外部应用程序中的控制器或处理器,如下所示:

application.yml
                        spring:
  cloud:
    gateway:
      routes:
      - id: ingredients
        uri: lb://ingredients
        predicates:
        - Path=//ingredients/**
        filters:
        - name: CircuitBreaker
          args:
            name: fetchIngredients
            fallbackUri: forward:/fallback
      - id: ingredients-fallback
        uri: http://localhost:9994
        predicates:
        - Path=/fallback

                    
yaml

在这个例子中,网关应用程序中没有 fallback 端点或处理器。但是在另一个注册在 localhost:9994 下的应用程序中有一个。

当请求被转发到 fallback 时,Spring Cloud CircuitBreaker Gateway 过滤器还会提供导致它的 Throwable。它被添加到 ServerWebExchange 中作为 ServerWebExchangeUtils.CIRCUITBREAKER_EXECUTION_EXCEPTION_ATTR 属性,可以在网关应用程序内处理 fallback 时使用。

对于外部控制器/处理器场景,可以添加包含异常详细信息的 headers。你可以在 FallbackHeaders GatewayFilter Factory 部分找到更多相关信息。

基于状态码触发断路器

在某些情况下,你可能想要基于路由返回的状态码来触发断路器。断路器配置对象接受一个状态码列表,如果返回这些状态码,将导致断路器被触发。在设置要触发断路器的状态码时,你可以使用状态码的整数值或 HttpStatus 枚举的字符串表示。

application.yml
                        spring:
  cloud:
    gateway:
      routes:
      - id: circuitbreaker_route
        uri: lb://backing-service:8088
        predicates:
        - Path=/consumingServiceEndpoint
        filters:
        - name: CircuitBreaker
          args:
            name: myCircuitBreaker
            fallbackUri: forward:/inCaseOfFailureUseThis
            statusCodes:
              - 500
              - "NOT_FOUND"

                    
yaml
Application.java
                        @Bean
public RouteLocator routes(RouteLocatorBuilder builder) {
    return builder.routes()
        .route("circuitbreaker_route", r -> r.path("/consumingServiceEndpoint")
            .filters(f -> f.circuitBreaker(c -> c.name("myCircuitBreaker")
                .fallbackUri("forward:/inCaseOfFailureUseThis")
                .addStatusCode("INTERNAL_SERVER_ERROR")))
                .rewritePath("/consumingServiceEndpoint", "/backingServiceEndpoint"))
                .uri("lb://backing-service:8088")
        .build();
}

                    
java

CacheRequestBody GatewayFilter 工厂

某些情况下需要读取请求体。由于请求体只能被读取一次,我们需要缓存请求体。你可以使用 CacheRequestBody 过滤器在发送请求到下游之前缓存请求体,并从 exchange 属性中获取请求体。

下面的例子展示了如何配置 CacheRequestBody GatewayFilter:

Application.java
                        @Bean
public RouteLocator routes(RouteLocatorBuilder builder) {
    return builder.routes()
        .route("cache_request_body_route", r -> r.path("/downstream/**")
            .filters(f -> f.prefixPath("/httpbin")
                .cacheRequestBody(String.class).uri(uri))
        .build();
}

                    
java
application.yml
                        spring:
  cloud:
    gateway:
      routes:
      - id: cache_request_body_route
        uri: lb://downstream
        predicates:
        - Path=/downstream/**
        filters:
        - name: CacheRequestBody
          args:
            bodyClass: java.lang.String

                    
yaml

CacheRequestBody 会提取请求体并将其转换为指定的 body class(如上例中定义的 java.lang.String)。然后 CacheRequestBody 会将其放入 ServerWebExchange.getAttributes() 可获取的属性中,使用 ServerWebExchangeUtils.CACHED_REQUEST_BODY_ATTR 作为键。

注意

此过滤器仅适用于 HTTP(包括 HTTPS)请求。

DedupeResponseHeader GatewayFilter 工厂

DedupeResponseHeader GatewayFilter 工厂需要一个 name 参数和一个可选的 strategy 参数。name 可以包含以空格分隔的多个 header 名称。下面的例子展示了如何配置一个 DedupeResponseHeader GatewayFilter:

application.yml
                        spring:
  cloud:
    gateway:
      routes:
      - id: dedupe_response_header_route
        uri: https://example.org
        filters:
        - DedupeResponseHeader=Access-Control-Allow-Credentials Access-Control-Allow-Origin

                    
yaml

这个配置会在网关的 CORS 逻辑和下游逻辑都添加了这些 header 的情况下,删除重复的 Access-Control-Allow-CredentialsAccess-Control-Allow-Origin 响应头。

DedupeResponseHeader 过滤器还接受一个可选的 strategy 参数。可接受的值包括:

  • RETAIN_FIRST(默认值):保留第一个值
  • RETAIN_LAST:保留最后一个值
  • RETAIN_UNIQUE:保留所有唯一值

FallbackHeaders GatewayFilter 工厂

FallbackHeaders 工厂允许你在请求被转发到外部应用程序的 fallbackUri 时,在请求头中添加 Spring Cloud CircuitBreaker 执行异常的详细信息,如下面的场景所示:

application.yml
                        spring:
  cloud:
    gateway:
      routes:
      - id: ingredients
        uri: lb://ingredients
        predicates:
        - Path=//ingredients/**
        filters:
        - name: CircuitBreaker
          args:
            name: fetchIngredients
            fallbackUri: forward:/fallback
      - id: ingredients-fallback
        uri: http://localhost:9994
        predicates:
        - Path=/fallback
        filters:
        - name: FallbackHeaders
          args:
            executionExceptionTypeHeaderName: Test-Header

                    
yaml

在这个例子中,当运行断路器时发生执行异常后,请求会被转发到运行在 localhost:9994 的应用程序中的 fallback 端点或处理器。FallbackHeaders 过滤器会将包含异常类型、消息以及(如果可用)根本原因异常类型和消息的 headers 添加到该请求中。

你可以在配置中通过设置以下参数的值来覆盖 headers 的名称(显示的是默认值):

  • executionExceptionTypeHeaderName"Execution-Exception-Type"
  • executionExceptionMessageHeaderName"Execution-Exception-Message"
  • rootCauseExceptionTypeHeaderName"Root-Cause-Exception-Type"
  • rootCauseExceptionMessageHeaderName"Root-Cause-Exception-Message"

关于断路器和网关的更多信息,请参见 Spring Cloud CircuitBreaker Factory 部分。

JsonToGrpc GatewayFilter 工厂

JsonToGrpc GatewayFilter 工厂用于将 JSON 负载转换为 gRPC 请求。

过滤器接受以下参数:

  • protoDescriptor:Proto 描述符文件。

该文件可以使用 protoc 并指定 --descriptor_set_out 标志来生成:

                        protoc --proto_path=src/main/resources/proto/ \
--descriptor_set_out=src/main/resources/proto/hello.pb  \
src/main/resources/proto/hello.proto

                    
bash
  • protoFile:Proto 定义文件。
  • service处理请的务的短名
  • method:服务中处理请求的方法名称。
注意

不支持流式传输。

下面是配置示例:

Application.java
                        @Bean
public RouteLocator routes(RouteLocatorBuilder builder) {
    return builder.routes()
            .route("json-grpc", r -> r.path("/json/hello").filters(f -> {
                String protoDescriptor = "file:src/main/proto/hello.pb";
                String protoFile = "file:src/main/proto/hello.proto";
                String service = "HelloService";
                String method = "hello";
                return f.jsonToGRPC(protoDescriptor, protoFile, service, method);
            }).uri(uri))

                    
java
application.yml
                        spring:
  cloud:
    gateway:
      routes:
        - id: json-grpc
          uri: https://localhost:6565/testhello
          predicates:
            - Path=/json/**
          filters:
            - name: JsonToGrpc
              args:
                protoDescriptor: file:proto/hello.pb
                protoFile: file:proto/hello.proto
                service: HelloService
                method: hello

                    
yaml

当通过网关向 /json/hello 发出请求时,请求会使用 hello.proto 中提供的定义进行转换,发送到 HelloService/hello,响应会被转换回 JSON。

默认情况下,它使用默认的 TrustManagerFactory 创建一个 NettyChannel。但是,你可以通过创建一个 GrpcSslConfigurer 类型的 bean 来自定义这个 TrustManager

GRPCLocalConfiguration.java
                        @Configuration
public class GRPCLocalConfiguration {
    @Bean
    public GRPCSSLContext sslContext() {
        TrustManager trustManager = trustAllCerts();
        return new GRPCSSLContext(trustManager);
    }
}

                    
java

LocalResponseCache GatewayFilter 工厂

该过滤器允许缓存响应体和响应头,遵循以下规则:

  • 只能缓存无请求体的 GET 请求。
  • 只缓存以下状态码的响应:HTTP 200 (OK)、HTTP 206 (Partial Content) 或 HTTP 301 (Moved Permanently)。
  • 如果 Cache-Control 头不允许缓存(请求中存在 no-store 或响应中存在 no-storeprivate),则不会缓存响应数据。
  • 如果响应已被缓存,且新请求的 Cache-Control 头中包含 no-cache 值,则返回一个无响应体的 304 (Not Modified) 响应。

该过滤器可以为每个路由配置本地响应缓存,但只有在启用 spring.cloud.gateway.filter.local-response-cache.enabled 属性时才可用。同时,全局配置的本地响应缓存也可以作为特性使用。

它接受第一个参数来覆盖缓存条目的过期时间(使用 s 表示秒,m 表示分钟,h 表示小时),第二个参数用于设置该路由的缓存最大大小(KBMBGB)。

下面的例子展示了如何添加本地响应缓存 GatewayFilter

Application.java
                        @Bean
public RouteLocator routes(RouteLocatorBuilder builder) {
    return builder.routes()
        .route("rewrite_response_upper", r -> r.host("*.rewriteresponseupper.org")
            .filters(f -> f.prefixPath("/httpbin")
                .localResponseCache(Duration.ofMinutes(30), "500MB")
            ).uri(uri))
        .build();
}

                    
java

或者使用 YAML 配置:

application.yml
                        spring:
  cloud:
    gateway:
      routes:
      - id: resource
        uri: http://localhost:9000
        predicates:
        - Path=/resource
        filters:
        - LocalResponseCache=30m,500MB

                    
yaml
注意

此过滤器还会自动计算 HTTP Cache-Control 头中的 max-age 值。只有当原始响应中存在 max-age 时,才会使用 timeToLive 配置参数中设置的秒数重写该值。在后续调用中,这个值会根据响应过期前剩余的秒数重新计算。

注意

要启用此功能,需要添加 com.github.ben-manes.caffeine:caffeine 和 spring-boot-starter-cache 作为项目依赖。

注意

如果你的项目创建了自定义的 CacheManager beans,则需要使用 @Primary 标记或使用 @Qualifier 注入。

MapRequestHeader GatewayFilter 工厂

MapRequestHeader GatewayFilter 工厂需要 fromHeadertoHeader 两个参数。它会创建一个新的命名 header(toHeader),其值从传入的 HTTP 请求中已存在的命名 header(fromHeader)中提取。如果输入的 header 不存在,过滤器不会产生任何影响。如果新命名的 header 已经存在,其值会与新值合并。下面的例子展示了如何配置一个 MapRequestHeader GatewayFilter:

application.yml
                        spring:
  cloud:
    gateway:
      routes:
      - id: map_request_header_route
        uri: https://example.org
        filters:
        - MapRequestHeader=Blue, X-Request-Red

                    
yaml

这个配置会从传入的 HTTP 请求的 Blue header 中获取值,并将这些值添加到发送给下游请求的 X-Request-Red header 中。

ModifyRequestBody GatewayFilter 工厂

你可以使用 ModifyRequestBody 过滤器在请求被网关发送到下游之前修改请求体。

注意

此过滤器只能通过 Java DSL 方式进行配置。

下面的例子展示了如何配置一个修改请求体的 GatewayFilter:

Application.java
                        @Bean
public RouteLocator routes(RouteLocatorBuilder builder) {
    return builder.routes()
        .route("rewrite_request_obj", r -> r.host("*.rewriterequestobj.org")
            .filters(f -> f.prefixPath("/httpbin")
                .modifyRequestBody(String.class, Hello.class, MediaType.APPLICATION_JSON_VALUE,
                    (exchange, s) -> Mono.just(new Hello(s.toUpperCase())))).uri(uri))
        .build();
}

static class Hello {
    String message;

    public Hello() { }

    public Hello(String message) {
        this.message = message;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

                    
java
注意

如果请求没有请求体,RewriteFilter 会收到 null。应该返回 Mono.empty() 来表示请求中缺少请求体。

ModifyResponseBody GatewayFilter 工厂

你可以使用 ModifyResponseBody 过滤器在响应发送回客户端之前修改响应体。

注意

此过滤器只能通过 Java DSL 方式进行配置。

下面的例子展示了如何配置一个修改响应体的 GatewayFilter:

Application.java
                        @Bean
public RouteLocator routes(RouteLocatorBuilder builder) {
    return builder.routes()
        .route("rewrite_response_upper", r -> r.host("*.rewriteresponseupper.org")
            .filters(f -> f.prefixPath("/httpbin")
                .modifyResponseBody(String.class, String.class,
                    (exchange, s) -> Mono.just(s.toUpperCase()))).uri(uri))
        .build();
}

                    
java
注意

如果响应没有响应体,RewriteFilter 会收到 null。应该返回 Mono.empty() 来表示响应中缺少响应体。

PrefixPath GatewayFilter 工厂

PrefixPath GatewayFilter 工厂接受一个 prefix 参数。下面的例子展示了如何配置一个 PrefixPath GatewayFilter:

application.yml
                        spring:
  cloud:
    gateway:
      routes:
      - id: prefixpath_route
        uri: https://example.org
        filters:
        - PrefixPath=/mypath

                    
yaml

这个配置会为所有匹配的请求路径添加前缀 /mypath。例如,对 /hello 的请求会被发送到 /mypath/hello

PreserveHostHeader GatewayFilter 工厂

PreserveHostHeader GatewayFilter 工厂没有参数。该过滤器设置一个请求属性,路由过滤器会检查这个属性来决定是发送原始的 host header 还是由 HTTP 客户端确定的 host header。下面的例子展示了如何配置一个 PreserveHostHeader GatewayFilter:

application.yml
                        spring:
  cloud:
    gateway:
      routes:
      - id: preserve_host_route
        uri: https://example.org
        filters:
        - PreserveHostHeader

                    
yaml

RedirectTo GatewayFilter 工厂

RedirectTo GatewayFilter 工厂需要三个参数:statusurl 和可选的 includeRequestParamsstatus 参数应该是一个 300 系列的重定向 HTTP 状态码,比如 301。url 参数应该是一个有效的 URL,这个值会被设置到 Location 头中。includeRequestParams 参数表示是否应该在 url 中包含请求查询参数。如果未设置,将被视为 false。对于相对重定向,你应该在路由定义中使用 uri: no://op。下面的例子展示了如何配置一个 RedirectTo GatewayFilter:

application.yml
                        spring:
  cloud:
    gateway:
      routes:
      - id: prefixpath_route
        uri: https://example.org
        filters:
        - RedirectTo=302, https://acme.org

                    
yaml

这个配置会发送一个状态码为 302 的响应,并带有 Location:https://acme.org 头来执行重定向。

下面的例子展示了如何配置一个带有 includeRequestParams 设置为 trueRedirectTo GatewayFilter:

application.yml
                        spring:
  cloud:
    gateway:
      routes:
      - id: prefixpath_route
        uri: https://example.org
        filters:
        - RedirectTo=302, https://acme.org, true

                    
yaml

当向网关发送带有查询参数 $1skip=10 的请求时,网关会发送一个状态码为 302 的响应,并带有 Location:https://acme.org$2skip=10 头来执行重定向。

RemoveJsonAttributesResponseBody GatewayFilter 工厂

RemoveJsonAttributesResponseBody GatewayFilter 工厂接受一个属性名称集合作为搜索目标,最后一个可选参数可以是一个布尔值,用于指定是仅删除根级别的属性(如果未在参数配置末尾指定,则默认为 false)还是递归删除(true)。它提供了一种通过删除属性来转换 JSON 响应体内容的便捷方法。

下面的例子展示了如何配置一个 RemoveJsonAttributesResponseBody GatewayFilter:

application.yml
                        spring:
  cloud:
    gateway:
      routes:
      - id: removejsonattributes_route
        uri: https://example.org
        filters:
        - RemoveJsonAttributesResponseBody=id,color

                    
yaml

这个配置会从 JSON 响应体的根级别删除 "id" 和 "color" 属性。

下面的例子展示了如何配置一个使用可选的最后一个参数的 RemoveJsonAttributesResponseBody GatewayFilter:

application.yml
                        spring:
  cloud:
    gateway:
      routes:
      - id: removejsonattributes_recursively_route
        uri: https://example.org
        predicates:
        - Path=/red/{segment}
        filters:
        - RemoveJsonAttributesResponseBody=id,color,true

                    
yaml

这个配置会从 JSON 响应体的所有层级删除 "id" 和 "color" 属性。

RemoveRequestHeader GatewayFilter 工厂

RemoveRequestHeader GatewayFilter 工厂需要一个 name 参数。这个参数是要被删除的 header 的名称。下面的例子展示了如何配置一个 RemoveRequestHeader GatewayFilter:

application.yml
                        spring:
  cloud:
    gateway:
      routes:
      - id: removerequestheader_route
        uri: https://example.org
        filters:
        - RemoveRequestHeader=X-Request-Foo

                    
yaml

这个配置会在请求发送到下游之前删除 X-Request-Foo header。

RemoveRequestParameter GatewayFilter 工厂

RemoveRequestParameter GatewayFilter 工厂需要一个 name 参数。这个参数是要被删除的查询参数的名称。下面的例子展示了如何配置一个 RemoveRequestParameter GatewayFilter:

application.yml
                        spring:
  cloud:
    gateway:
      routes:
      - id: removerequestparameter_route
        uri: https://example.org
        filters:
        - RemoveRequestParameter=red

                    
yaml

这个配置会在请求发送到下游之前删除 red 查询参数。

RemoveResponseHeader GatewayFilter 工厂

RemoveResponseHeader GatewayFilter 工厂需要一个 name 参数。这个参数是要被删除的 header 的名称。下面的例子展示了如何配置一个 RemoveResponseHeader GatewayFilter:

application.yml
                        spring:
  cloud:
    gateway:
      routes:
      - id: removeresponseheader_route
        uri: https://example.org
        filters:
        - RemoveResponseHeader=X-Response-Foo

                    
yaml

这个配置会在响应返回到网关客户端之前删除 X-Response-Foo header。

要删除任何敏感的 header,你应该为可能需要这样做的所有路由配置此过滤器。此外,你可以使用 spring.cloud.gateway.default-filters 配置一次此过滤器,使其应用于所有路由。

RequestHeaderSize GatewayFilter 工厂

RequestHeaderSize GatewayFilter 工厂需要 maxSizeerrorHeaderName 两个参数。maxSize 参数是请求头允许的最大数据大小(包括键和值)。errorHeaderName 参数设置包含错误消息的响应头的名称,默认为 "errorMessage"。下面的例子展示了如何配置一个 RequestHeaderSize GatewayFilter:

application.yml
                        spring:
  cloud:
    gateway:
      routes:
      - id: requestheadersize_route
        uri: https://example.org
        filters:
        - RequestHeaderSize=1000B

                    
yaml

如果任何请求头的大小超过 1000 字节,这个配置会返回状态码 431。

RequestRateLimiter GatewayFilter 工厂

RequestRateLimiter GatewayFilter 工厂使用 RateLimiter 实现来确定当前请求是否允许继续处理。如果不允许,则返回 HTTP 429 - Too Many Requests(默认)状态码。

这个过滤器接受一个可选的 keyResolver 参数和特定于限流器的参数(在本节后面描述)。

keyResolver 是一个实现了 KeyResolver 接口的 bean。在配置中,使用 SpEL 表达式通过名称引用这个 bean。#{@myKeyResolver} 是一个 SpEL 表达式,它引用了一个名为 myKeyResolver 的 bean。下面是 KeyResolver 接口的定义:

KeyResolver.java
                        public interface KeyResolver {
    Mono<String> resolve(ServerWebExchange exchange);
}

                    
java

KeyResolver 接口允许插入可插拔的策略来派生限流的键。在未来的里程碑版本中,将会提供一些 KeyResolver 实现。

KeyResolver 的默认实现是 PrincipalNameKeyResolver,它从 ServerWebExchange 中获取 Principal 并调用 Principal.getName()

默认情况下,如果 KeyResolver 找不到键,请求会被拒绝。你可以通过设置 spring.cloud.gateway.filter.request-rate-limiter.deny-empty-keytruefalse)和 spring.cloud.gateway.filter.request-rate-limiter.empty-key-status-code 属性来调整这个行为。

注意

RequestRateLimiter 不能使用"快捷"方式配置。以下示例是无效的

application.properties
                        # 无效的快捷配置
spring.cloud.gateway.routes[0].filters[0]=RequestRateLimiter=2, 2, #{@userkeyresolver}

                    
properties

这是一个有效的 yaml 配置示例:

application.yml
                        spring:
  cloud:
    gateway:
      routes:
      - id: limit
        uri: https://example.org
        filters:
        - name: RequestRateLimiter
          args:
            key-resolver: "#{@userkeyresolver}"

                    
yaml

Redis RateLimiter

Redis 实现基于 Stripe 的工作。它需要使用 spring-boot-starter-data-redis-reactive Spring Boot starter。

使用的算法令牌桶算法。

redis-rate-limiter.replenishRate 属性定义了每秒允许多少个请求(不会丢弃何请求)。这是令牌桶填充的速率。

redis-rate-limiter.burstCapacity 属性是用户在一秒钟内允许的最大请求数(不会丢弃任何请求)。这是令牌桶可以容纳的令牌数量。将此值设置为零会阻止所有请求。

redis-rate-limiter.requestedTokens 属性一个请求需要消耗多少令牌。这是每个请求从桶中取出的令牌数,默认为 1

通过在 replenishRateburstCapacity 中设置相同的值可以实现稳定的速率。通过将 burstCapacity 设置为高于 replenishRate 可以允许临时突发。在这种情况下,限流器需要在突发之后留出一些时间(根据 replenishRate),因为两个连续的突发会导致请求被丢弃(返回 HTTP 429 - Too Many Requests)。

要实现低于每秒 1 个请求的速率限制,可以通过设置 replenishRate 为所需的请求数,requestedTokens 为秒数,burstCapacityreplenishRaterequestedTokens 的乘积来实现。例如,设置 replenishRate=1requestedTokens=60burstCapacity=60 会得到每分钟 1 个请求的限制。

下面的例子配置了一个 Redis RateLimiter:

application.yml
                        spring:
  cloud:
    gateway:
      routes:
      - id: requestratelimiter_route
        uri: https://example.org
        filters:
        - name: RequestRateLimiter
          args:
            redis-rate-limiter.replenishRate: 10
            redis-rate-limiter.burstCapacity: 20
            redis-rate-limiter.requestedTokens: 1

                    
yaml

下面的例子在 Java 中配置了一个 KeyResolver

Config.java
                        @Bean
KeyResolver userKeyResolver() {
    return exchange -> Mono.just(exchange.getRequest().getQueryParams().getFirst("user"));
}

                    
java

这定义了每个用户每秒 10 个请求的限制。允许 20 个请求的突发,但在下一秒只有 10 个请求可用。KeyResolver 是一个简单的实现,它获取 user 请求参数。注意:这不建议在生产环境中使用。

你也可以定义一个实现 RateLimiter 接口的限流器 bean。在配置中,你可以使用 SpEL 表达式通过名称引用这个 bean。#{@myRateLimiter} 是一个 SpEL 表达式,它引用了一个名为 myRateLimiter 的 bean。下面的例子使用前面示例中定义的 KeyResolver 定义了一个限流器:

application.yml
                        spring:
  cloud:
    gateway:
      routes:
      - id: requestratelimiter_route
        uri: https://example.org
        filters:
        - name: RequestRateLimiter
          args:
            rate-limiter: "#{@myRateLimiter}"
            key-resolver: "#{@userKeyResolver}"

                    
yaml

RewriteLocationResponseHeader GatewayFilter 工厂

RewriteLocationResponseHeader GatewayFilter 工厂用于修改 Location 响应头的值,通常用于去除后端特定的细节。它接受 ModelocationHeaderNamehostValueprotocols 参数。下面的例子展示了如何配置一个 RewriteLocationResponseHeader GatewayFilter:

application.yml
                        spring:
  cloud:
    gateway:
      routes:
      - id: rewritelocationresponseheader_route
        uri: http://example.org
        filters:
        - RewriteLocationResponseHeader=AS_IN_REQUEST, Location, ,

                    
yaml

例如,对于请求 POST api.example.com/some/object/nameLocation 响应头的值 object-service.prod.example.net/v2/some/object/id 会被重写为 api.example.com/some/object/id

Mode 参数有以下可能的值:NEVER_STRIPAS_IN_REQUEST(默认值)和 ALWAYS_STRIP

  • NEVER_STRIP:即使原始请求路径不包含版本,也不会去除版本。
  • AS_IN_REQUEST:只有当原始请求路径不包含版本时,才会去除版本。
  • ALWAYS_STRIP:即使原始请求路径包含版本,也总是去除版本。

如果提供了 hostValue 参数,它会被用来替换响应 Location 头中的 host:port 部分。如果未提供,则使用请求的 Host 头的值。

protocols 参数必须是一个有效的正则表达式字符串,用于匹配协议名称。如果不匹配,过滤器不会执行任何操作。默认值是 https$3|ftps$4

RewritePath GatewayFilter 工厂

RewritePath GatewayFilter 工厂需要一个路径 regexp 参数和一个 replacement 参数。它使用 Java 正则表达式来灵活地重写请求路径。下面的例子展示了如何配置一个 RewritePath GatewayFilter:

application.yml
                        spring:
  cloud:
    gateway:
      routes:
      - id: rewritepath_route
        uri: https://example.org
        predicates:
        - Path=/red/**
        filters:
        - RewritePath=/red/$7($8<segment>.*), /$\{segment}

                    
yaml

对于请求路径 /red/blue,这个配置会在发送下游请求之前将路径设置为 /blue。注意:由于 YAML 规范的要求,$ 应该被替换为 $\

RewriteRequestParameter GatewayFilter 工厂

RewriteRequestParameter GatewayFilter 工厂需要一个 name 参数和一个 replacement 参数。它会重写指定 name 的请求参数的值。如果设置了多个同名的请求参数,它们会被替换为单个值。如果找不到请求参数,则不会进行任何更改。下面的例子展示了如何配置一个 RewriteRequestParameter GatewayFilter:

application.yml
                        spring:
  cloud:
    gateway:
      routes:
      - id: rewriterequestparameter_route
        uri: https://example.org
        predicates:
        - Path=/products
        filters:
        - RewriteRequestParameter=campaign,fall2023

                    
yaml

对于请求 /products$9campaign=old,这个配置会将请求参数设置为 campaign=fall2023

RewriteResponseHeader GatewayFilter 工厂

RewriteResponseHeader GatewayFilter 工厂需要 nameregexpreplacement 参数。它使用 Java 正则表达式来灵活地重写响应头的值。下面的例子展示了如何配置一个 RewriteResponseHeader GatewayFilter:

application.yml
                        spring:
  cloud:
    gateway:
      routes:
      - id: rewriteresponseheader_route
        uri: https://example.org
        filters:
        - RewriteResponseHeader=X-Response-Red, , password=[^&]+, password=***

                    
yaml

对于响应头值为 /42$10user=ford&password=omg!what&flag=true,在发送下游请求后会被设置为 /42$11user=ford&password=***&flag=true。注意:由于 YAML 规范的要求,你必须使用 $\ 来表示 $

SaveSession GatewayFilter 工厂

SaveSession GatewayFilter 工厂会在转发调用到下游之前强制执行 WebSession::save 操作。当使用 Spring Session 搭配懒加载数据存储时,这个功能特别有用,因为你需要确保会话状态在进行转发调用之前已经被保存。下面的例子展示了如何配置一个 SaveSession GatewayFilter:

application.yml
                        spring:
  cloud:
    gateway:
      routes:
      - id: save_session
        uri: https://example.org
        predicates:
        - Path=/foo/**
        filters:
        - SaveSession

                    
yaml

如果你将 Spring Security 与 Spring Session 集成,并且想要确保安全细节被转发到远程进程,这个配置是至关重要的。

SecureHeaders GatewayFilter 工厂

SecureHeaders GatewayFilter 工厂会根据安全建议向响应中添加一系列 headers。

以下是添加的 headers(显示的是默认值):

  • X-Xss-Protection:1 (mode=block)
  • Strict-Transport-Security (max-age=631138519)
  • X-Frame-Options (DENY)
  • X-Content-Type-Options (nosniff)
  • Referrer-Policy (no-referrer)
  • Content-Security-Policy (default-src 'self' https:; font-src 'self' https: data:; img-src 'self' https: data:; object-src 'none'; script-src https:; style-src 'self' https: 'unsafe-inline')
  • X-Download-Options (noopen)
  • X-Permitted-Cross-Domain-Policies (none)

要修改默认值,可以在 spring.cloud.gateway.filter.secure-headers 命名空间下设置相应的属性。可用的属性包括:

  • xss-protection-header
  • strict-transport-security
  • frame-options
  • content-type-options
  • referrer-policy
  • content-security-policy
  • download-options
  • permitted-cross-domain-policies

要禁用默认值,可以使用逗号分隔的值设置 spring.cloud.gateway.filter.secure-headers.disable 属性。下面的例子展示了如何做到这一点:

application.properties
                        spring.cloud.gateway.filter.secure-headers.disable=x-frame-options,strict-transport-security

                    
properties
注意

需要使用安全头的小写全名来禁用它。

SetPath GatewayFilter 工厂

SetPath GatewayFilter 工厂需要一个路径 template 参数。它提供了一种简单的方式来操作请求路径,允许使用模板化的路径段。它使用 Spring Framework 的 URI 模板功能。允许使用多个匹配段。下面的例子展示了如何配置一个 SetPath GatewayFilter:

application.yml
                        spring:
  cloud:
    gateway:
      routes:
      - id: setpath_route
        uri: https://example.org
        predicates:
        - Path=/red/{segment}
        filters:
        - SetPath=/{segment}

                    
yaml

对于请求路径 /red/blue,这个配置会在发送下游请求之前将路径设置为 /blue

SetRequestHeader GatewayFilter 工厂

SetRequestHeader GatewayFilter 工厂需要 namevalue 参数。下面的例子展示了如何配置一个 SetRequestHeader GatewayFilter:

application.yml
                        spring:
  cloud:
    gateway:
      routes:
      - id: setrequestheader_route
        uri: https://example.org
        filters:
        - SetRequestHeader=X-Request-Red, Blue

                    
yaml

这个 GatewayFilter 会替换(而不是添加)所有具有给定名称的 header。因此,如果下游服务器响应中包含 X-Request-Red:1234,它将被替换为 X-Request-Red:Blue,这就是下游服务将收到的内容。

SetRequestHeader 能够识别用于匹配路径或主机的 URI 变量。URI 变量可以在 value 中使用,并在运行时展开。下面的例子配置了一个使用变量的 SetRequestHeader GatewayFilter:

application.yml
                        spring:
  cloud:
    gateway:
      routes:
      - id: setrequestheader_route
        uri: https://example.org
        predicates:
        - Host: {segment}.myhost.org
        filters:
        - SetRequestHeader=foo, bar-{segment}

                    
yaml

SetResponseHeader GatewayFilter 工厂

SetResponseHeader GatewayFilter 工厂需要 namevalue 参数。下面的例子展示了如何配置一个 SetResponseHeader GatewayFilter:

application.yml
                        spring:
  cloud:
    gateway:
      routes:
      - id: setresponseheader_route
        uri: https://example.org
        filters:
        - SetResponseHeader=X-Response-Red, Blue

                    
yaml

这个 GatewayFilter 会替换(而不是添加)所有具有给定名称的 header。因此,如果下游服务器响应中包含 X-Response-Red:1234,它将被替换为 X-Response-Red:Blue,这就是网关客户端将收到的内容。

SetResponseHeader 能够识别用于匹配路径或主机的 URI 变量。URI 变量可以在 value 中使用,并在运行时展开。下面的例子配置了一个使用变量的 SetResponseHeader GatewayFilter:

application.yml
                        spring:
  cloud:
    gateway:
      routes:
      - id: setresponseheader_route
        uri: https://example.org
        predicates:
        - Host: {segment}.myhost.org
        filters:
        - SetResponseHeader=foo, bar-{segment}

                    
yaml

SetStatus GatewayFilter 工厂

SetStatus GatewayFilter 工厂需要一个 status 参数。它必须是一个有效的 Spring HttpStatus。可以是整数值 404 或枚举的字符串表示:NOT_FOUND。下面的例子展示了如何配置一个 SetStatus GatewayFilter:

application.yml
                        spring:
  cloud:
    gateway:
      routes:
      - id: setstatusstring_route
        uri: https://example.org
        filters:
        - SetStatus=UNAUTHORIZED
      - id: setstatusint_route
        uri: https://example.org
        filters:
        - SetStatus=401

                    
yaml

在这两种情况下,响应的 HTTP 状态码都会被设置为 401。

你可以配置 SetStatus GatewayFilter 在响应的一个 header 中返回代理请求的原始 HTTP 状态码。通过以下属性配置后,header 会被添加到响应中:

application.yml
                        spring:
  cloud:
    gateway:
      set-status:
        original-status-header-name: original-http-status

                    
yaml

StripPrefix GatewayFilter 工厂

StripPrefix GatewayFilter 工厂需要一个 parts 参数。parts 参数表示在将请求发送到下游之前,要从请求路径中去除的路径段数量。下面的例子展示了如何配置一个 StripPrefix GatewayFilter:

application.yml
                        spring:
  cloud:
    gateway:
      routes:
      - id: nameRoot
        uri: https://nameservice
        predicates:
        - Path=/name/**
        filters:
        - StripPrefix=2

                    
yaml

当通过网关向 /name/blue/red 发出请求时,发送到 nameservice 的请求路径会变成 /red

Retry GatewayFilter 工厂

Retry GatewayFilter 工厂支持以下参数:

  • retries:应该尝试的重试次数。
  • statuses:应该重试的 HTTP 状态码,使用 org.springframework.http.HttpStatus 表示。
  • methods:应该重试的 HTTP 方法,使用 org.springframework.http.HttpMethod 表示。
  • series:应该重试的状态码系列,使用 org.springframework.http.HttpStatus.Series 表示。
  • exceptions:应该重试的异常列表。
  • backoff:重试的指数退避配置。重试会在 firstBackoff * (factor ^ n) 的退避间隔后执行,其中 n 是迭代次数。如果配置了 maxBackoff,则应用的最大退避时间将限制为 maxBackoff。如果 basedOnPreviousValue 为 true,则退避时间使用 prevBackoff * factor 计算。

如果启用了 Retry 过滤器,以下是默认配置:

  • retries:3 次
  • series:5XX 系列
  • methods:GET 方法
  • exceptionsIOExceptionTimeoutException
  • backoff:禁用

下面的例子配置了一个 Retry GatewayFilter:

application.yml
                        spring:
  cloud:
    gateway:
      routes:
      - id: retry_test
        uri: http://localhost:8080/flakey
        predicates:
        - Host=*.retry.com
        filters:
        - name: Retry
          args:
            retries: 3
            statuses: BAD_GATEWAY
            methods: GET,POST
            backoff:
              firstBackoff: 10ms
              maxBackoff: 50ms
              factor: 2
              basedOnPreviousValue: false

                    
yaml
注意

当使用带有 forward: 前缀的 URL 的重试过滤器时,目标端点应该谨慎编写,以便在发生错误时不会执行任何可能导致响应被发送到客户端并提交的操作。例如,如果目标端点是一个带注解的控制器,目标控制器方法不应返回带有错误状态码的 ResponseEntity。相反,它应该抛出异常或发出错误信号(例如,通过 Mono.error(ex) 返回值),重试过滤器可以配置为通过重试来处理这种情况。

注意

使用重试过滤器时,它会重试其后的所有过滤器。确保重试过滤器后面的过滤器在多次执行时的结果符合预期。

注意

当使用重试过滤器处理带有请求体的任何 HTTP 方法时,请求体将被缓存,网关将受到内存限制。请求体被缓存在由 ServerWebExchangeUtils.CACHED_REQUEST_BODY_ATTR 定义的请求属性中。对象的类型是 org.springframework.core.io.buffer.DataBuffer。

可以使用简化的"快捷"表示法添加单个 statusmethod

以下两个例子是等效的:

application.yml
                        spring:
  cloud:
    gateway:
      routes:
      - id: retry_route
        uri: https://example.org
        filters:
        - name: Retry
          args:
            retries: 3
            statuses: INTERNAL_SERVER_ERROR
            methods: GET
            backoff:
              firstBackoff: 10ms
              maxBackoff: 50ms
              factor: 2
              basedOnPreviousValue: false

      - id: retryshortcut_route
        uri: https://example.org
        filters:
        - Retry=3,INTERNAL_SERVER_ERROR,GET,10ms,50ms,2,false

                    
yaml

RequestSize GatewayFilter 工厂

当请求大小超过允许的限制时,RequestSize GatewayFilter 工厂可以阻止请求到达下游服务。该过滤器接受一个 maxSize 参数。maxSizeDataSize 类型,因此值可以定义为一个数字后跟一个可选的 DataUnit 后缀,如 'KB' 或 'MB'。默认单位是 'B'(字节)。这个值定义了请求的允许大小限制(以字节为单位)。下面的例子展示了如何配置一个 RequestSize GatewayFilter:

application.yml
                        spring:
  cloud:
    gateway:
      routes:
      - id: request_size_route
        uri: http://localhost:8080/upload
        predicates:
        - Path=/upload
        filters:
        - name: RequestSize
          args:
            maxSize: 5000000

                    
yaml

当请求因大小原因被拒绝时,RequestSize GatewayFilter 工厂会将响应状态设置为 413 Payload Too Large,并添加一个额外的 errorMessage 头。下面是一个这样的 errorMessage 示例:

                        errorMessage : Request size is larger than permissible limit. Request size is 6.0 MB where permissible limit is 5.0 MB

                    
text
注意

如果在路由定义中未提供过滤器参数,则默认请求大小限制为 5MB。

SetRequestHostHeader GatewayFilter 工厂

在某些情况下,可能需要覆盖 host 头。在这种情况下,SetRequestHostHeader GatewayFilter 工厂可以用指定的值替换现有的 host 头。该过滤器接受一个 host 参数。下面的例子展示了如何配置一个 SetRequestHostHeader GatewayFilter:

application.yml
                        spring:
  cloud:
    gateway:
      routes:
      - id: set_request_host_header_route
        uri: http://localhost:8080/headers
        predicates:
        - Path=/headers
        filters:
        - name: SetRequestHostHeader
          args:
            host: example.org

                    
yaml

SetRequestHostHeader GatewayFilter 工厂会将 host 头的值替换为 example.org

TokenRelay GatewayFilter 工厂

令牌中继是指 OAuth2 消费者作为客户端,将传入的令牌转发到传出的资源请求。消费者可以是纯客户端(如 SSO 应用程序)或资源服务器。

Spring Cloud Gateway 可以使用 TokenRelay GatewayFilter 将 OAuth2 访问令牌转发到它所代理的下游服务。

TokenRelay GatewayFilter 接受一个可选参数 clientRegistrationId。下面的例子展示了如何配置一个 TokenRelay GatewayFilter:

App.java
                        @Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
    return builder.routes()
            .route("resource", r -> r.path("/resource")
                    .filters(f -> f.tokenRelay("myregistrationid"))
                    .uri("http://localhost:9000"))
            .build();
}

                    
java

或者使用 YAML 配置:

application.yml
                        spring:
  cloud:
    gateway:
      routes:
      - id: resource
        uri: http://localhost:9000
        predicates:
        - Path=/resource
        filters:
        - TokenRelay=myregistrationid

                    
yaml

上面的例子指定了一个 clientRegistrationId,它可以用于获取并转发任何可用 ClientRegistration 的 OAuth2 访问令牌。

Spring Cloud Gateway 还可以转发当前已认证用户的 OAuth2 访问令牌(使用 oauth2Login() 认证用户时)。要在网关中添加此功能,你可以省略 clientRegistrationId 参数,如下所示:

App.java
                        @Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
    return builder.routes()
            .route("resource", r -> r.path("/resource")
                    .filters(f -> f.tokenRelay())
                    .uri("http://localhost:9000"))
            .build();
}

                    
java

或者使用 YAML 配置:

application.yml
                        spring:
  cloud:
    gateway:
      routes:
      - id: resource
        uri: http://localhost:9000
        predicates:
        - Path=/resource
        filters:
        - TokenRelay=

                    
yaml

这样配置后,它会(除了登录用户并获取令牌外)将认证令牌传递给下游服务(在本例中是 /resource)。

要为 Spring Cloud Gateway 启用此功能,需要添加以下依赖:

  • org.springframework.boot:spring-boot-starter-oauth2-client

工作原理是什么?过滤器会从当前已认证用户中提取指定 clientRegistrationId 的 OAuth2 访问令牌。如果未提供 clientRegistrationId,则使用用户登录时获取的访问令牌。在任何情况下,提取的访问令牌都会被放置在请求头中,用于下游请求。

注意

只有在设置了适当的 spring.security.oauth2.client.* 属性(这会触发创建 ReactiveClientRegistrationRepository bean)时,才会创建 TokenRelayGatewayFilterFactory bean。

注意

TokenRelayGatewayFilterFactory 使用的默认 ReactiveOAuth2AuthorizedClientService 实现使用内存数据存储。如果需要更健壮的解决方案,你需要提供自己的 ReactiveOAuth2AuthorizedClientService 实现。

默认过滤器

要添加过滤器并将其应用于所有路由,你可以使用 spring.cloud.gateway.default-filters 属性。这个属性接受一个过滤器列表。下面的例子定义了一组默认过滤器:

application.yml
                        spring:
  cloud:
    gateway:
      default-filters:
      - AddResponseHeader=X-Response-Default-Red, Default-Blue
      - PrefixPath=/httpbin

                    
yaml