Spring Cloud Gateway内置Filter

参考:官方文档

Spring Cloud版本:Hoxton.SR5

Spring Cloud Gateway版本:2.2.3.RELEASE

1 简介

Filter可以以某种方式修改请求或者响应。Spring Cloud Gateway提供了很多内置的GatewayFilterFactory。这些filter只对配置的当前route有效。

2 内置的Filter

2.1 AddRequestHeaderGatewayFilterFactory

AddRequestHeaderGatewayFilterFactory能够给请求添加Header内容。它接受两个参数,一个是Header中的属性名name,一个是属性值value

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

如上配置,将会为请求添加X-Request-color:blue的头部信息。

2.2 AddRequestParameterGatewayFilterFactory

AddRequestParameterGatewayFilterFactory 能够为请求添加参数。它接受两个参数,一个是参数的名name,一个是参数的值value

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

如上配置,将会为请求添加请求参数color=red

2.3 AddResponseHeaderGatewayFilterFactory

AddResponseHeaderGatewayFilterFactory将会为响应添加Header内容。它接受两个参数,一个是Header中的属性名name,一个是属性值value

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

如上配置,将会为响应添加X-Response-color:Blue的头部信息。

2.4 DedupeResponseHeaderGatewayFilterFactory

DedupeResponseHeaderGatewayFilterFactory可以剔除响应头中的重读值。它接受两个参数,一个是name参数,一个是可选的策略strategy参数。name参数可以填写多个值,用空格隔开,表示要剔除的Header中的属性名。

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-CredentialsAccess-Control-Allow-Origin

策略strategy有三种选择:

  • RETAIN_FIRST:保留第一个值,默认策略。
  • RETAIN_LAST:保留最后一个值。
  • RETAIN_UNIQUE:保留所有唯一值,以它们第一次出现的顺序保留。

2.5 HystrixGatewayFilterFactory

Netflix已经将Hystrix进入维护模式,官方建议使用SpringCloudCircuitBreakerFilterFactory

2.6 SpringCloudCircuitBreakerFilterFactory

SpringCloudCircuitBreakerFilterFactory使用Spring Cloud CircuitBreaker APIs将网关路由封装在熔断器中。

Spring Cloud CircuitBreaker支持在Spring Cloud Gateway中使用两种熔断器库,HystrixResilience4J。因为Hystrix已经进入维护阶段,所以官方建议使用Resilience4J

如果要使用SpringCloudCircuitBreakerFilterFactory,需要在项目中引入熔断器的依赖spring-cloud-starter-circuitbreaker-reactor-resilience4j或者spring-cloud-starter-netflix-hystrix

下面展示了如何配置这个filter

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

如上,配置了一个熔断器。关于如何设置熔断器策略,可以查看文档:

并且,可以配置一个fallbackUri,当发生熔断的时候将会跳转这个地址。

spring:
  cloud:
    gateway:
      routes:
      - id: circuitbreaker_route
        uri: https://example.org
        filters:
        - name: CircuitBreaker
          args:
            name: myCircuitBreaker
            fallbackUri: forward:/inCaseOfFailureUseThis
        - RewritePath=/consumingServiceEndpoint, /backingServiceEndpoint

2.7 FallbackHeadersGatewayFilterFactory

FallbackHeadersGatewayFilterFactory可以在转发请求到fallbackUri的时候,为请求添加一个Header,这个Header的值为具体的异常信息。

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

2.8 MapRequestHeaderGatewayFilterFactory

MapRequestHeaderGatewayFilterFactory能够转换请求头的内容。它接受两个参数,一个是原请求头fromHeader,一个是转换后的请求头toHeader。如果原请求头不存在,这个过滤器将不起作用。如果转换后的请求头已经存在,它的值将会用新的值。

spring:
  cloud:
    gateway:
      routes:
      - id: map_request_header_route
        uri: https://example.org
        filters:
        - MapRequestHeader=X-Request-color, X-Request-newcolor

上面的配置,将会获取原请求头X-Request-color的内容,并转换为新的请求头X-Request-newcolor

2.9 PrefixPathGatewayFilterFactory

PrefixPathGatewayFilterFactory将会为请求的path添加前缀。

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

如上配置,将会为请求添加/mypath前缀。例如,/hello请求将会路由到/mypath/hello

2.10 PreserveHostHeaderGatewayFilterFactory

PreserveHostHeaderGatewayFilterFactory不接受参数。如果不设置,那么名为 HostHeaderHttp Client控制;如果设置了,那么会设置一个请求属性(preserveHostHeader=true),路由过滤器会检查从而去判断是否要发送原始的、名为HostHeader

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

2.11 RequestRateLimiterGatewayFilterFactory

RequestRateLimiterGatewayFilterFactory可以对请求进行限流。它使用RateLimiter的实现来判断当前请求是否可以通过,如果被限流了,默认将会返回HTTP 429 - Too Many Requests

详细内容,可以查看RequestRateLimiterGatewayFilterFactory

2.12 RedirectToGatewayFilterFactory

RedirectToGatewayFilterFactory能够重定向请求。它接受两个参数,一个是状态status,一个是urlstatus的值应该是300系列的HTTP状态码,例如301url应该是一个有效的地址,它是HeaderLocation属性的值。

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

如上配置,将会发送302状态码,并携带Location:https://acme.org的请求头信息。

2.13 RemoveRequestHeaderGatewayFilterFactory

RemoveRequestHeaderGatewayFilterFactory可以移除请求头中的信息。它接受一个name参数,表示将要移除的头部中的信息名称。

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

如上配置,将会移除请求头中X-Request-Foo信息。

2.14 RemoveRequestParameterGatewayFilterFactory

RemoveRequestParameterGatewayFilterFactory能够移除请求参数。它接受一个name参数,表示将要移除的请求参数名称。

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

如上配置,将会移除请求中的color参数。

2.15 RemoveResponseHeaderGatewayFilterFactory

RemoveResponseHeaderGatewayFilterFactory能够移除响应头中的信息。它接受一个name参数,表示将要移除的响应头中的信息名称。

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

如上配置,将会移除响应头中的X-Response-Foo信息。

2.16 RewritePathGatewayFilterFactory

RewritePathGatewayFilterFactory能够重写请求路径。它接受一个描述path的正则表达式,和一个替换表达式。

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

如上配置,如果请求是/red/blue,那么重写的后的路径是/blue,注意由于YAML规范,要用$\替换为$

2.17 RewriteLocationResponseHeaderGatewayFilterFactory

RewriteLocationResponseHeaderGatewayFilterFactory能够修改响应头中的Location属性的值。它接受stripVersionlocationHeaderNamehostValueprotocols参数。

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

stripVersion可选三个值:

  • NEVER_STRIP:即使原始请求路径不包含版本,版本也不会被删除。
  • AS_IN_REQUEST:(默认值),只有当原始请求路径不包含版本时,版本才会被删除。
  • ALWAYS_STRIP:即使原始请求路径包含版本,版本也总是被删除。

hostValue如果指定了,将会替换响应头中Location中的host:port部分。

protocols部分必须是一个有效的表示请求协议的正则表达式。默认值是http|https|ftp|ftps

2.18 RewriteResponseHeaderGatewayFilterFactory

RewriteResponseHeaderGatewayFilterFactory能够重写响应头中的属性。它接受三个参数,name表示响应头中的属性名,regexp表示一个正则表达式,用来匹配name对应的值,replacement表示匹配之后重写的值。

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

如上配置,假设响应头中X-Response-Red属性的值为/42?user=ford&password=omg!what&flag=true,将会被替换成/42?user=ford&password=***&flag=true,其中password的部分被替换了。

2.19 SaveSessionGatewayFilterFactory

SaveSessionGatewayFilterFactory能够强制执行WebSession::save操作。当使用Spring Session与懒加载数据存储之类的东西时,这是特别有用的,并且需要确保在转发调用之前已保存会话状态。

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

如果要将Spring SecuritySpring Session集成,并且希望确保将安全性详细信息转发到远程进程,则这很关键。

2.20 SecureHeadersGatewayFilterFactory

SecureHeadersGatewayFilterFactory会给响应头加上如下内容:

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来设置:

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

2.21 SetPathGatewayFilterFactory

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

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

如上配置,如果请求路径是/red/blue,路径将会被设置为/blue

2.22 SetRequestHeaderGatewayFilterFactory

SetRequestHeaderGatewayFilterFactory能够设置请求头。它接受两个参数,一个是属性名name,一个是属性值value

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

这个filter能够根据name替换请求头中的value,注意不是添加一个header属性。

这个filter的配置中也可以使用URI变量,形如{value}。如下:

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

2.23 SetResponseHeaderGatewayFilterFactory

SetResponseHeaderGatewayFilterFactory能够设置响应头。它接受两个参数,一个是属性名name,一个是属性值value

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

这个filter能够根据name替换响应头中的value,注意不是添加一个header属性。

这个filter的配置中也可以使用URI变量,形如{value}。如下:

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

2.24 SetStatusGatewayFilterFactory

SetStatusGatewayFilterFactory能够设置HTTP状态码。它接受一个status值,必须是Spring中的HttpStatus中的有效值,可以是数字,也可以是字符串。

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

2.25 StripPrefixGatewayFilterFactory

StripPrefixGatewayFilterFactory可以对请求路径进行处理,根据传入的参数parts值,剥离路径个数。

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

例如上述配置,如果请求的urlhttps://nameservice/name/blue/red,那么请求的路径path则是/name/blue/red,根据配置

StripPrefix=2需要剥离请求中的路径个数为2,也就是删除name/blue,则最终请求的url变为https://nameservice/red

2.26 RetryGatewayFilterFactory

RetryGatewayFilterFactory能够在转发请求到下游不通的时候,进行重试。

它接受如下参数:

  • retries:应该尝试的重试次数。
  • statuses:指定出现哪些HTTP状态码的时候需要重试,取值org.springframework.http.HttpStatus
  • methods:指定针对哪些HTTP请求方法需要重试,取值org.springframework.http.HttpMethod
  • series:用来指定出现哪些类的HTTP状态码需要重试,取值org.springframework.http.HttpStatus.Series
  • exceptions:用来指定出现哪些异常的时候需要重试。
  • backoff

默认情况下,取值:

  • retries: 3次。
  • series: 5XX系列的状态码。
  • methods: GET请求。
  • exceptions: IOExceptionTimeoutException
  • backoff: disabled
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

2.27 RequestSizeGatewayFilterFactory

RequestSizeGatewayFilterFactory可以对请求大小进行限制,当请求的大小大于这个filter设置的限制值的时候,filter会拦截请求,不转发到下游服务器。

它接受一个maxSize参数,用来限制请求内容的最大值,单位为Byte

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

请求大小超过最大值,filter将会返回一个413 Payload Too Large的状态码信息,并在header中附带一个errorMessage信息。例如:

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

如果不指定最大值,默认是5MB

2.28 SetRequestHostHeaderGatewayFilterFactory

SetRequestHostHeaderGatewayFilterFactory能够修改Header中的host信息。

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

2.29 DefaultFilters

如果想要添加一批filter并对所有route有效,可以使用spring.cloud.gateway.default-filters。它接受一个filter列表。

spring:
  cloud:
    gateway:
      default-filters:
      - AddResponseHeader=X-Response-Default-Red, Default-Blue
      - PrefixPath=/httpbin
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值