Spring Cloud Alibaba study notes (18) - Spring Cloud Gateway built-in filter plant

Reference: https: //cloud.spring.io/spring-cloud-static/spring-cloud-gateway/2.1.0.RELEASE/single/spring-cloud-gateway.html#_gatewayfilter_factories

AddRequestHeader GatewayFilter Factory

Header added to the original request, a configuration example: add name X-Request-Foo, Bar request header to the value of the original request

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

AddRequestParameter GatewayFilter Factory

The original request and the request to add the value of the parameter, a configuration example: add to the original request named foo, bar parameter value, i.e.: foo = bar

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

AddResponseHeader GatewayFilter Factory

Header added to the original response, a configuration example: addition response header called X-Request-Foo, in response to the original value of Bar

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

DedupeResponseHeader GatewayFilter Factory

Us on Gateway and micro services are set CORS (cross-domain resolved) Header, and if do not do any configuration, then the request -> Gateway -> Micro service, value CORS Header obtained, it will be like this:

Access-Control-Allow-Credentials: true, true
Access-Control-Allow-Origin: https://musk.mars, https://musk.mars

Header can see these two values ​​are repeated, if you want these two values ​​Header deduplication, then you need to use to DedupeResponseHeader, configuration examples:

spring:
  cloud:
    gateway:
      routes:
      - id: dedupe_response_header_route
        uri: https://example.org
        filters:
        # 若需要去重的Header有多个,使用空格分隔
        - DedupeResponseHeader=Access-Control-Allow-Credentials Access-Control-Allow-Origin

De-duplication strategy:

  • RETAIN_FIRST: defaults, retains the first value
  • RETAIN_LAST: Hold Last Value
  • RETAIN_UNIQUE: keep all unique values ​​in the order they first appeared reserved

PS: New Features Spring Cloud Greenwich SR2 provided below this version can not be used.

Hystrix GatewayFilter Factory

Hystrix routing circuit breaker protection is introduced, a configuration example:

spring:
  cloud:
    gateway:
      routes:
      - id: hystrix_route
        uri: https://example.org
        filters:
        - Hystrix=myCommandName

PS: Hystrix Spring Cloud is the first generation of fault-tolerant components, but has entered the maintenance mode, the future Hystrix Spring Cloud will be removed off, replaced by Alibaba Sentinel / Resilience4J.

FallbackHeaders GatewayFilter Factory

Hystrix the same support, described in the previous section supports a filter plant configuration parameters: fallbackUri, this configuration is used when an abnormality occurs forwards the request to a specific uri. And this filtration plant FallbackHeaders Header can be added when a request is forwarded to the uri, the specific value of the abnormality information in Header. Configuration example:

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

PrefixPath GatewayFilter Factory

Add a prefix to the original path of the request path, configuration: This configuration enables access $ {GATEWAY_URL} / hello forwarded to https://example.org/mypath/hello

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

PreserveHostHeader GatewayFilter Factory

Add a request attribute preserveHostHeader = true, the filter checks the route to determine whether to send the attribute original Host Header. Configuration example:

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

If not set, then Header by Http Client control is called Host

RequestRateLimiter GatewayFilter Factory

For limiting the request, limiting the token bucket algorithm. Configuration example:

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

RedirectTo GatewayFilter Factory

The original request redirected to the specified Url, a configuration example:

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

This configuration enables access $ {GATEWAY_URL} / hello is redirected to https://acme.org/hello, and carries a Location: http: //acme.org the Header, the client returns an HTTP status code 302
the PS :

  • HTTP status code should 3xx, 301 e.g.
  • URL must be a valid URL, which will be as the value of the Location Header

RemoveHopByHopHeadersFilter GatewayFilter Factory

The original request to delete the IETF defined a series of Header, Header default deleted as follows:

  • Connection
  • Keep-Alive
  • Proxy-Authenticate
  • Proxy-Authorization
  • TO
  • Trailer
  • Transfer-Encoding
  • Upgrade
    can be configured to specify which deleted only Header, configuration examples:
spring:
  cloud:
    gateway:
      filter:
        remove-hop-by-hop:
          # 多个Header使用逗号(,)分隔
          headers: Connection,Keep-Alive

RemoveRequestHeader GatewayFilter Factory

The original request removal of a Header, a configuration example: X-Request-Foo original request to delete request header named

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

RemoveResponseHeader GatewayFilter Factory

Delete the original response to a Header, a configuration example: in response to the first X-Request-Foo delete the original response is named

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

RewritePath GatewayFilter Factory

Regular expression by rewriting the original path of the request, a configuration example:

spring:
  cloud:
    gateway:
      routes:
      - id: rewritepath_route
        uri: https://example.org
        predicates:
        - Path=/foo/**
        filters:
        # 参数1为原始路径的正则表达式,参数2为重写后路径的正则表达式
        - RewritePath=/foo/(?<segment>.*), /$\{segment}

When configured such that the access / foo / bar, the path will be rewritten to / bar then forwards, i.e. forwarded to https://example.org/bar. Note: Because YAML syntax required to replace $ $

RewriteResponseHeader GatewayFilter Factory

Overwrite the original in response to a Header, a configuration example:

spring:
  cloud:
    gateway:
      routes:
      - id: rewriteresponseheader_route
        uri: https://example.org
        filters:
        # 参数1为Header名称,参数2为值的正则表达式,参数3为重写后的值
        - RewriteResponseHeader=X-Response-Foo, password=[^&]+, password=***

The significance of this configuration is that:? If the response header X-Response-Foo value / 42 user = ford & password = omg what & flag = true, it will be rewritten in accordance with the value of the configuration of the / 42 is User = Ford & password =!? & In Flag = true, that is, to which the password = omg! what became rewrite password =

SaveSession GatewayFilter Factory

Before forwarding the request, the enforcement WebSession :: save operation, configuration example:

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

Mainly used in kind of like Spring Session delay data stored (data not immediately persistence) and want to ensure that the session state save situations before forwarding the request. If you will be in Spring Session Spring Secutiry integrated use, and want to ensure the security of information transmitted to the downstream machine, you need to configure the filter.

secureHeaders GatewayFilter Factory

secureHeaders filter plant for your safety added a series of response headers to the original response. The default will be added as follows Headers (including value):

  • 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

If you want to modify the values ​​of these Header, then you need to use these Headers corresponding suffix, as follows:

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

Configuration example:

spring:
  cloud:
    gateway:
      filter:
        secure-headers:
          # 修改 X-Xss-Protection 的值为 2; mode=unblock
          xss-protection-header: 2; mode=unblock

If you want to disable some of the Header, use the following configuration:

spring:
  cloud:
    gateway:
      filter:
        secure-headers:
          # 多个使用逗号(,)分隔
          disable: frame-options,download-options

SetPath GatewayFilter Factory

Modify the original request path, a configuration example:

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

This configuration enables forwards when access $ {GATEWAY_URL} / foo / bar to https://example.org/bar, i.e. the original / foo / bar to be modified / bar

SetResponseHeader GatewayFilter Factory

Header value of a modification of the original response, the configuration example: the original value in response to X-Response-Foo Bar modifies

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

SetStatus GatewayFilter Factory

Modify the original response status code, a configuration example:

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

SetStatusd value can be a number, or a string. But it must be a value HttpStatus Spring enumeration class. Both the above configuration can return the HTTP 401 status code.

StripPrefix GatewayFilter Factory

Cut path for the original request, a configuration example:

spring:
  cloud:
    gateway:
      routes:
      - id: nameRoot
        uri: http://nameservice
        predicates:
        - Path=/name/**
        filters:
        # 数字表示要截断的路径的数量
        - StripPrefix=2

If the path request is / name / bar / foo, it will be truncated to / forwarding after foo, that is, will cut two paths.

Retry GatewayFilter Factory

For different retry response, for example, a retry for HTTP status code, a configuration example:

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

Parameters may be configured as follows:

  • retries: number of retries
  • statuses: status code needs to be retried, the value in org.springframework.http.HttpStatus
  • methods: Method a request needs to be retried, the value in org.springframework.http.HttpMethod
  • series: HTTP status code sequence, the value in org.springframework.http.HttpStatus.Series

RequestSize GatewayFilter Factory

Receiving a maximum allowed setting request packet size, a configuration example: If the requested packet size exceeds the set value, 413 Payload Too Large and will return a errorMessage

spring:
  cloud:
    gateway:
      routes:
      - id: request_size_route
      uri: http://localhost:8080/upload
      predicates:
      - Path=/upload
      filters:
      - name: RequestSize
        args:
          # 单位为字节
          maxSize: 5000000

Modify Request Body GatewayFilter Factory

Modify the original content request before forwarding the request body, only through the filter plant code configuration, the configuration is not supported in the configuration file. Code Example:

@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;
    }
}

The filter plant is in BETA state, the API may change in the future, the production environment with caution

Modify Response Body GatewayFilter Factory

Response may be used to modify the contents of the original body, the filter code is configured by only the same plant, not supported in the configuration file. Code Example:

@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();
}

The filter plant is in BETA state, the API may change in the future, the production environment with caution

Default Filters

Default Filters used to add all routes filter plant, that is configured Default Filter through filter factory will act on all the routes. Configuration example:

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

Guess you like

Origin www.cnblogs.com/fx-blog/p/11751977.html