Spring Cloud Gateway 使用说明(2)-- 路由filter (下)

6.15 删除请求参数

RemoveRequestParameter  可以删除指定名称的请求参数:

Example 40. application.yml

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

请求下发前,参数red会被删除。

6.16 重写地址

RewritePath 包含一个 regexp正则表达式参数和一个 replacement 参数. 通过使用Java正则表达式灵活地重写请求路径。

Example 41. application.yml

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

对于请求路径/red/blue,将在发出下游请求之前将路径设置为/blue。注意,由于YAML规范,请使用 $\替换 $

6.17 重写location header

RewriteLocationResponseHeader  可以修改 Location header的值,从而隐藏一些后台路径细节。它的参数有stripVersionMode、locationHeaderName、hostValue和protocolsRegex。

Example 42. application.yml

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

比如,有一个请求 POST api.example.com/some/object/name ,响应中Location header的值原来是object-service.prod.example.net/v2/some/object/id ,会被修改为api.example.com/some/object/id

stripVersionMode参数有三个取值:NEVER_STRIP、AS_IN_REQUEST(默认)和 ALWAYS_STRIP

  • NEVER_STRIP: 不删除路径中的版本号
  • AS_IN_REQUEST:如果请求中没有版本号,则响应中的版本号会被删除
  • ALWAYS_STRIP: 删除路径中的版本号

如果提供了hostValue参数, 会用来替换掉响应中Location header的host:port 部分。如果没有提供该参数,则会使用请求中带的值。

protocolsRegex参数 必须要可以正确匹配到合法的协议名,否则不会产生效果。默认值是http|https|ftp|ftps。

6.18 修改响应header值

RewriteResponseHeader包含 name, regexpreplacement 参数.。通过使用Java正则表达式灵活地重写响应头的值。

Example 43. application.yml

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

对于一个/42?user=ford&password=omg!what&flag=true的header值,在做下游请求时将被设置为/42?user=ford&password=***&flag=true,由于YAML规范,请使用 $\替换 $

6.19 保存session

SaveSession GatewayFilter 将请求转发到下游之强制执行WebSession::save 操作。这在使用 Spring Session 之类时特别有用,需要确保会话状态在进行转发调用之前已保存。

Example 44. application.yml

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

如果你希望要将[Spring Security](https://projects.spring.io/Spring Security/)与Spring Session集成,并确保安全详细信息已转发到远程的进程,这一点至关重要。


6.20 添加 SecureHeaders

SecureHeaders GatewayFilter 可以把以下header添加到响应头中(带默认值):

  • 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)

对于这些header的详细说明,请看 HTTP Security Headers

spring.cloud.gateway.filter.secure-headers 中对应的属性如下:

  • xss-protection-header

  • strict-transport-security

  • x-frame-options

  • x-content-type-options

  • referrer-policy

  • content-security-policy

  • x-download-options

  • x-permitted-cross-domain-policies

下面的配置展示如何禁用默认header:

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

header名称要用小写

6.21 修改请求路径

SetPath GatewayFilter Factory 采用 template路径参数。它提供了一种通过允许路径的模板化segments来操作请求路径的简单方法。使用Spring Framework中的URI模板,允许多个匹配segments。


Example 45. application.yml

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

对于一个 /red/bar请求,在做下游请求前,路径将被设置为/bar

6.22 设置请求header

SetRequestHeader 需要指定 header的 name 和 value。

Example 46. application.yml

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

这个filter 替换(不添加)指定的header。以上的配置会把 X-Request-Red:1234 替换为X-Request-Red:Blue。

SetRequestHeader 也可能使用URI变量匹配 path或host, 运行时改变header值:

Example 47. application.yml

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

6.23 设置响应header

SetResponseHeader GatewayFilter Factory 包括 namevalue 参数.

Example 48. application.yml

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

此GatewayFilter使用给定的名称替换所有header,而不是添加。因此,如果下游服务器响应为X-Response-Red:1234,则会将其替换为X-Response-Red:Blue,这是网关客户端将接收的内容。

SetResponseHeader 也可能使用URI变量匹配 path或host, 运行时改变header值:

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

6.24 设置httpstatus

SetStatus GatewayFilter Factory 包括唯一的 status参数.必须是一个可用的Spring HttpStatus。它可以是整数值404或字符串枚举NOT_FOUND

Example 50. application.yml

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

在这个例子中,HTTP返回码将设置为401.

也可设置为返回原请求的状态码:

Example 51. application.yml

spring:
  cloud:
    gateway:
      set-status:
        original-status-header-name: original-http-status

6.25 截取请求地址

StripPrefix GatewayFilter Factory 包括一个parts参数。 parts参数指示在将请求发送到下游之前,要从请求中去除的路径中的节数。

Example 52. application.yml

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

当通过网关发出/name/bar/foo请求时,向nameservice发出的请求将是http://nameservice/foo

6.26 重试

Retry GatewayFilter Factory包括 以下参数:

  • 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。

如果开启重试功能,各个参数的默认值为:

  • retries: 3 次

  • series: 5XX series

  • methods: GET method

  • exceptions: IOException 和 TimeoutException

  • backoff: disabled

Example 53. 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
说明:

当 retry filter和 forward: 一起用的时候, 目标地址通过返回错误码的方式通知错误时,
不会触发重试;只有抛出异常或Mono.error(ex)的方式,才会触发重试。
注意:

重试时,如果请求中包含body,网关会缓存body,从而导致内存吃紧。 
保存缓存的属性为ServerWebExchangeUtils.CACHED_REQUEST_BODY_ATTR,
类型为org.springframework.core.io.buffer.DataBuffer

6.27 限制请求大小

RequestSize GatewayFilter Factory可以限制请求大小。过滤器以RequestSize作为参数,这是定义请求的允许大小限制。参数可以带位置,如 'KB' 或 'MB' , 默认是 ‘B’

Example 54. application.yml

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

当请求因大小而被拒绝时, RequestSize GatewayFilter Factory 将响应状态设置为413 Payload Too Large,并带有额外的header errorMessage 。下面是一个 errorMessage的例子。

errorMessage : Request size is larger than permissible limit. 
Request size is 6.0 MB where permissible limit is 5.0 MB
注意
如果未在路由定义中设置该参数,则默认请求大小将设置为5 MB。

6.28 修改请求host值

SetRequestHost filter可以把host修改为指定的值:

Example 55. application.yml

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

请求的host值会被修改为example.org

6.29 修改请求body

ModifyRequestBody可用于在请求主体被网关发送到下游之前对其进行修改。

注意
只能使用Java DSL配置此过滤器
@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) -> return 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;
    }
}

6.30 修改响应body

ModifyResponseBody可用于在将响应正文发送回客户端之前对其进行修改。

注意
只能使用Java DSL配置此过滤器
@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();
}

6.31 设置全局默认filters

spring.cloud.gateway.default-filters可以为所有路由添加默认filter列表:

Example 56. application.yml

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

Spring Cloud Gateway 2.2.3 官方使用说明(1)--路由

Spring Cloud Gateway 2.2.3 官方使用说明(2)-- 路由filter(上)

Spring Cloud Gateway 2.2.3 官方使用说明(2)-- 路由filter(下)

Spring Cloud Gateway 2.2.3 官方使用说明(3)-- Global filter

Spring Cloud Gateway 2.2.3 官方使用说明(4)-- HttpHeader Filters

Spring Cloud Gateway 2.2.3 使用说明(5)-- TLS 和 SSL

Spring Cloud Gateway 2.2.3 使用说明(6)-- 其它配置

Spring Cloud Gateway 2.2.3 使用说明(7)-- actuator

Spring Cloud Gateway 2.2.3 使用说明(8)-- 开发指导

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值