Spring Cloud Gateway

/ Spring Cloud / 没有评论 / 0浏览

link

Spring Cloud Gateway

2.2.0.M1

This project provides an API Gateway built on top of the Spring Ecosystem, including: Spring 5, Spring Boot 2 and Project Reactor. Spring Cloud Gateway aims to provide a simple, yet effective way to route to APIs and provide cross cutting concerns to them such as: security, monitoring/metrics, and resiliency.

该项目提供了一个建立在spring生态之上的网关,引入 spring 5,spring boot2 和 reactor 项目. spring cloud gateway 提供简单的功能,路由到api提供有效的方案,列如:安全,监控,指标

How to Include Spring Cloud Gateway

如何引入spring cloud gateway

To include Spring Cloud Gateway in your project use the starter with group org.springframework.cloud and artifact id spring-cloud-starter-gateway. See the Spring Cloud Project page for details on setting up your build system with the current Spring Cloud Release Train.

在项目pom文件中,加入  group `org.springframework.cloud` artifact `spring-cloud-starter-gateway`.引入spring cloud gateway,有关使用当前的详细构建系统的详细信息,请参阅 (https://projects.spring.io/spring-cloud/)

If you include the starter, but, for some reason, you do not want the gateway to be enabled, set spring.cloud.gateway.enabled=false.

如何你开始引用,但是由于某些原因,你不需要启用网关,设置 `spring.cloud.gateway.enabled=false`.

|   | Spring Cloud Gateway is built upon Spring Boot 2.0Spring WebFlux, and Project Reactor. As a consequence many of the familiar synchronous libraries (Spring Data and Spring Security, for example) and patterns you may not apply when using Spring Cloud Gateway. If you are unfamiliar with these projects we suggest you begin by reading their documentation to familiarize yourself with some of the new concepts before working with Spring Cloud Gateway. |

|   | Spring Cloud Gateway requires the Netty runtime provided by Spring Boot and Spring Webflux. It does not work in a traditional Servlet Container or built as a WAR. |

spring cloud gateway 构建在springboot2.0 和 spring webflux 响应式项目,因此,在使用spring cloud gateway时,许多常见的同步库和模式不太适用。如果你不熟悉这些项目,建议你在使用spring cloud gateway之前先阅读他们的文档,熟悉新的概念

spring cloud gateway 需要spring boot 和 spring webflux 提供的nettty 上运行,他不能在传统的servlet容器中工作,也不能作为war构建

Glossary

路由时网关的基础构建。它由Id定义,一个目的的URL,断言集合和过滤器集合,如果断言为true,则匹配集合
这是一个在java8中的函数Predicate,输入的类型时spring framework ServerWebExchange,这允许开发人员匹配http请求中的任何内容,可以时heard,parameters
特定工厂构造出的gatewayFilter实例,可以在发送下游请求之前或之后修改请求和相应

How It Works

它时如何运作的

Spring Cloud Gateway Diagram

Clients make requests to Spring Cloud Gateway. If the Gateway Handler Mapping determines that a request matches a Route, it is sent to the Gateway Web Handler. This handler runs sends the request through a filter chain that is specific to the request. The reason the filters are divided by the dotted line, is that filters may execute logic before the proxy request is sent or after. All "pre" filter logic is executed, then the proxy request is made. After the proxy request is made, the "post" filter logic is executed.

|   | URIs defined in routes without a port will get a default port set to 80 and 443 for HTTP and HTTPS URIs respectively. |

客户端像spring cloud gateway发出请求,如果这个网关处理映射确定到请求的路由上,则会发送到gateway web handler,处理通过特定请求过滤器链发送请求,过滤连被虚线分割的原因。过滤连在请求发送代理请求之前或之后执行逻辑。执行所有 pro链的逻辑部分,然后发出代理请求,在发出代理之后,执行 post 过滤器链。

在没有端口的路由中定义的url将得到http 和 https uri默认端口分别时80 和 443

Route Predicate Factories

Spring Cloud Gateway matches routes as part of the Spring WebFlux HandlerMapping infrastructure. Spring Cloud Gateway includes many built-in Route Predicate Factories. All of these predicates match on different attributes of the HTTP request. Multiple Route Predicate Factories can be combined and are combined via logical and.

spring cloud gateway 将匹配路由作为spring webflux handlerMapping基础的一部分,spring cloud gateway 提供许多内置断言工厂,所有这些断言匹配http请求的不同属性,可以组合多个断言匹配规则,通过逻辑组合他们。

After Route Predicate Factory

The After Route Predicate Factory takes one parameter, a datetime. This predicate matches requests that happen after the current datetime.

这 after 断言工厂接受一个参数,一个时间戳,当前时间之后发送的请求。

application.yml

spring:
  cloud:
    gateway:
      routes:
      - id: after_route
        uri: https://example.org
        predicates:
        - After=2017-01-20T17:42:47.789-07:00[America/Denver]

This route matches any request after Jan 20, 2017 17:42 Mountain Time (Denver).

Before Route Predicate Factory

The Before Route Predicate Factory takes one parameter, a datetime. This predicate matches requests that happen before the current datetime.

这 after 断言工厂接受一个参数,一个时间戳,当前时间之前发送的请求。

application.yml

spring:
  cloud:
    gateway:
      routes:
      - id: before_route
        uri: https://example.org
        predicates:
        - Before=2017-01-20T17:42:47.789-07:00[America/Denver]

This route matches any request before Jan 20, 2017 17:42 Mountain Time (Denver).

Between Route Predicate Factory

The Between Route Predicate Factory takes two parameters, datetime1 and datetime2. This predicate matches requests that happen after datetime1 and before datetime2. The datetime2 parameter must be after datetime1.

这 after 断言工厂接受一个参数,一个时间戳,当前时间之间发送的请求。

application.yml

spring:
  cloud:
    gateway:
      routes:
      - id: between_route
        uri: https://example.org
        predicates:
        - Between=2017-01-20T17:42:47.789-07:00[America/Denver], 2017-01-21T17:42:47.789-07:00[America/Denver]

This route matches any request after Jan 20, 2017 17:42 Mountain Time (Denver) and before Jan 21, 2017 17:42 Mountain Time (Denver). This could be useful for maintenance windows.

Cookie Route Predicate Factory

The Cookie Route Predicate Factory takes two parameters, the cookie name and a regular expression. This predicate matches cookies that have the given name and the value matches the regular expression.

cookie 路由断言工厂接受俩个参数,cookie名称和value(可以正则表达式)

application.yml

spring:
  cloud:
    gateway:
      routes:
      - id: cookie_route
        uri: https://example.org
        predicates:
        - Cookie=chocolate, ch.p

This route matches the request has a cookie named chocolate who’s value matches the ch.p regular expression.

Header Route Predicate Factory

The Header Route Predicate Factory takes two parameters, the header name and a regular expression. This predicate matches with a header that has the given name and the value matches the regular expression.

hearder 路由断言工厂接受俩个参数,name名称和value(可以正则表达式)

application.yml

spring:
  cloud:
    gateway:
      routes:
      - id: header_route
        uri: https://example.org
        predicates:
        - Header=X-Request-Id, \d+

This route matches if the request has a header named X-Request-Id whose value matches the \d+ regular expression (has a value of one or more digits).

Host Route Predicate Factory

The Host Route Predicate Factory takes one parameter: a list of host name patterns. The pattern is an Ant style pattern with . as the separator. This predicates matches the Host header that matches the pattern.

host 路由断言工厂接受一个参数,并支持集合匹配,逗号最为分隔符

application.yml

spring:
  cloud:
    gateway:
      routes:
      - id: host_route
        uri: https://example.org
        predicates:
        - Host=**.somehost.org,**.anotherhost.org

URI template variables are supported as well, such as {sub}.myhost.org.

This route would match if the request has a Host header has the value www.somehost.org or beta.somehost.org or www.anotherhost.org.

This predicate extracts the URI template variables (like sub defined in the example above) as a map of names and values and places it in the ServerWebExchange.getAttributes() with a key defined in ServerWebExchangeUtils.URI_TEMPLATE_VARIABLES_ATTRIBUTE. Those values are then available for use by GatewayFilter Factories

Method Route Predicate Factory

The Method Route Predicate Factory takes one parameter: the HTTP method to match.

application.yml

spring:
  cloud:
    gateway:
      routes:
      - id: method_route
        uri: https://example.org
        predicates:
        - Method=GET

This route would match if the request method was a GET.

Path Route Predicate Factory

The Path Route Predicate Factory takes two parameters: a list of Spring PathMatcher patterns and an optional flag to matchOptionalTrailingSeparator.

application.yml

spring:
  cloud:
    gateway:
      routes:
      - id: host_route
        uri: https://example.org
        predicates:
        - Path=/foo/{segment},/bar/{segment}

This route would match if the request path was, for example: /foo/1 or /foo/bar or /bar/baz.

This predicate extracts the URI template variables (like segment defined in the example above) as a map of names and values and places it in the ServerWebExchange.getAttributes() with a key defined in ServerWebExchangeUtils.URI_TEMPLATE_VARIABLES_ATTRIBUTE. Those values are then available for use by GatewayFilter Factories

A utility method is available to make access to these variables easier.

Map<String, String> uriVariables = ServerWebExchangeUtils.getPathPredicateVariables(exchange);

String segment = uriVariables.get("segment");

Query Route Predicate Factory

The Query Route Predicate Factory takes two parameters: a required param and an optional regexp.

application.yml

spring:
  cloud:
    gateway:
      routes:
      - id: query_route
        uri: https://example.org
        predicates:
        - Query=baz

This route would match if the request contained a baz query parameter.

application.yml

spring:
  cloud:
    gateway:
      routes:
      - id: query_route
        uri: https://example.org
        predicates:
        - Query=foo, ba.

This route would match if the request contained a foo query parameter whose value matched the ba. regexp, so bar and bazwould match.

RemoteAddr Route Predicate Factory

The RemoteAddr Route Predicate Factory takes a list (min size 1) of CIDR-notation (IPv4 or IPv6) strings, e.g. 192.168.0.1/16 (where 192.168.0.1 is an IP address and 16 is a subnet mask).

application.yml

spring:
  cloud:
    gateway:
      routes:
      - id: remoteaddr_route
        uri: https://example.org
        predicates:
        - RemoteAddr=192.168.1.1/24

This route would match if the remote address of the request was, for example, 192.168.1.10.

Modifying the way remote addresses are resolved

修改远程地址解析方式

By default the RemoteAddr Route Predicate Factory uses the remote address from the incoming request. This may not match the actual client IP address if Spring Cloud Gateway sits behind a proxy layer.

默认远程 地址路由断言工厂 使用来自远程的请求地址,如果spring cloud gateway位于代理层后面,这可能与时间的客户端ip不匹配

You can customize the way that the remote address is resolved by setting a custom RemoteAddressResolver. Spring Cloud Gateway comes with one non-default remote address resolver which is based off of the X-Forwarded-For header

XForwardedRemoteAddressResolver.

你可以通过自定义 RemoteAddressResolver 来设置远程地址解析,spring cloud gateway 提供了基于 header x-forwarded-for 默认的远程解析器

XForwardedRemoteAddressResolver has two static constructor methods which take different approaches to security:

XForwardedRemoteAddressResolver 有两个静态构造方法,采用不同的安全方式

XForwardedRemoteAddressResolver::trustAll returns a RemoteAddressResolver which always takes the first IP address found in the X-Forwarded-For header. This approach is vulnerable to spoofing, as a malicious client could set an initial value for the X-Forwarded-For which would be accepted by the resolver.

返回一个 RemoteAddressResolver 它总是返回 hearder 中 x-forwarded-for 第一个地址,这种方法容易受到欺骗干扰,如果恶意的用户设置 x-forwarded-for,解析将会获取这个地址

XForwardedRemoteAddressResolver::maxTrustedIndex takes an index which correlates to the number of trusted infrastructure running in front of Spring Cloud Gateway. If Spring Cloud Gateway is, for example only accessible via HAProxy, then a value of 1 should be used. If two hops of trusted infrastructure are required before Spring Cloud Gateway is accessible, then a value of 2 should be used.


Given the following header value:

X-Forwarded-For: 0.0.0.1, 0.0.0.2, 0.0.0.3

The maxTrustedIndex values below will yield the following remote addresses.

maxTrustedIndexresult

[Integer.MIN_VALUE,0]

|

(invalid, IllegalArgumentException during initialization)

| |

1

|

0.0.0.3

| |

2

|

0.0.0.2

| |

3

|

0.0.0.1

| |

[4, Integer.MAX_VALUE]

|

0.0.0.1

|

Using Java config:

GatewayConfig.java

RemoteAddressResolver resolver = XForwardedRemoteAddressResolver
    .maxTrustedIndex(1);

...

.route("direct-route",
    r -> r.remoteAddr("10.1.1.1", "10.10.1.1/24")
        .uri("https://downstream1")
.route("proxied-route",
    r -> r.remoteAddr(resolver,  "10.10.1.1", "10.10.1.1/24")
        .uri("https://downstream2")
)

GatewayFilter Factories

网关过滤器工厂

Route filters allow the modification of the incoming HTTP request or outgoing HTTP response in some manner. Route filters are scoped to a particular route. Spring Cloud Gateway includes many built-in GatewayFilter Factories.

路由过滤器允许已某种方式修改http 请求或http响应,路由过滤器的作用域是特定的路由,spring cloud 引入很多 网关过滤工厂

NOTE For more detailed examples on how to use any of the following filters, take a look at the unit tests.

有关如何使用一下过滤器的详细实例,请看这里 link

AddRequestHeader GatewayFilter Factory

The AddRequestHeader GatewayFilter Factory takes a name and value parameter.

AddRequestHeader GateFilter 工厂接受一个名称和参数值

application.yml

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

This will add X-Request-Foo:Bar header to the downstream request’s headers for all matching requests.

AddRequestParameter GatewayFilter Factory

The AddRequestParameter GatewayFilter Factory takes a name and value parameter.

application.yml

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

This will add foo=bar to the downstream request’s query string for all matching requests.

AddResponseHeader GatewayFilter Factory

The AddResponseHeader GatewayFilter Factory takes a name and value parameter.

application.yml

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

This will add X-Response-Foo:Bar header to the downstream response’s headers for all matching requests.

DedupeResponseHeader GatewayFilter Factory

The DedupeResponseHeader GatewayFilter Factory takes a name parameter and an optional strategy parameter. name can contain a list of header names, space separated.

DedupeResponseHeader GatewayFilter Factory采用名称参数和可选策略参数。 name可以包含标题名称列表,空格分隔。

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

This will remove duplicate values of Access-Control-Allow-Credentials and Access-Control-Allow-Origin response headers in cases when both the gateway CORS logic and the downstream add them.

在网关CORS逻辑和下游添加它们的情况下,这将删除Access-Control-Allow-Credentials和Access-Control-Allow-Origin响应头的重复值。

The DedupeResponseHeader filter also accepts an optional strategy parameter. The accepted values are RETAIN_FIRST (default), RETAIN_LAST, and RETAIN_UNIQUE.

DedupeResponseHeader过滤器还接受可选的`strategy`参数。 可接受的值是`RETAIN_FIRST`(默认值),`RETAIN_LAST`和`RETAIN_UNIQUE`。

Hystrix GatewayFilter Factory

Hystrix is a library from Netflix that implements the circuit breaker pattern. The Hystrix GatewayFilter allows you to introduce circuit breakers to your gateway routes, protecting your services from cascading failures and allowing you to provide fallback responses in the event of downstream failures.

To enable Hystrix GatewayFilters in your project, add a dependency on spring-cloud-starter-netflix-hystrix from Spring Cloud Netflix.

The Hystrix GatewayFilter Factory requires a single name parameter, which is the name of the HystrixCommand.

application.yml

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

This wraps the remaining filters in a HystrixCommand with command name myCommandName.

The Hystrix filter can also accept an optional fallbackUri parameter. Currently, only forward: schemed URIs are supported. If the fallback is called, the request will be forwarded to the controller matched by the URI.

application.yml

spring:
  cloud:
    gateway:
      routes:
      - id: hystrix_route
        uri: lb://backing-service:8088
        predicates:
        - Path=/consumingserviceendpoint
        filters:
        - name: Hystrix
          args:
            name: fallbackcmd
            fallbackUri: forward:/incaseoffailureusethis
        - RewritePath=/consumingserviceendpoint, /backingserviceendpoint

This will forward to the /incaseoffailureusethis URI when the Hystrix fallback is called. Note that this example also demonstrates (optional) Spring Cloud Netflix Ribbon load-balancing via the lb prefix on the destination URI.

当调用Hystrix后备时,这将转发到`/ incaseoffailureusethis` URI。 请注意,此示例还通过目标URI上的`lb`前缀演示(可选)Spring Cloud Netflix Ribbon负载平衡。

The primary scenario is to use the fallbackUri to an internal controller or handler within the gateway app. However, it is also possible to reroute the request to a controller or handler in an external application, like so:

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

application.yml

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

In this example, there is no fallback endpoint or handler in the gateway application, however, there is one in another app, registered under [http://localhost:9994](http://localhost:9994/).

在此示例中,网关应用程序中没有回退端点或处理程序,

In case of the request being forwarded to fallback, the Hystrix Gateway filter also provides the Throwable that has caused it. It’s added to the ServerWebExchange as the ServerWebExchangeUtils.HYSTRIX_EXECUTION_EXCEPTION_ATTR attribute that can be used when handling the fallback within the gateway app.

如果请求被转发到 fallback,Hystrix网关过滤器还提供了引发该问题的可丢弃性,
它作为ServerWebExchangeUtils添加到ServerWebExchange中。HYSTRIX_EXECUTION_EXCEPTION_ATTR属性,该属性可用于处理网关应用程序中的回退

For the external controller/ handler scenario, headers can be added with exception details. You can find more information on it in the FallbackHeaders GatewayFilter Factory section.

对于外部控制器/处理程序场景,可以添加带有异常详细信息的头。你可以在网站上找到更多的信息

Hystrix settings (such as timeouts) can be configured with global defaults or on a route by route basis using application properties as explained on the Hystrix wiki.

可以使用全局缺省值配置Hystrix设置(如超时),也可以使用应用程序属性按路由逐个路由地配置

To set a 5 second timeout for the example route above, the following configuration would be used:

要为上述示例路由设置5秒超时,将使用以下配置:

application.yml

hystrix.command.fallbackcmd.execution.isolation.thread.timeoutInMilliseconds: 5000

FallbackHeaders GatewayFilter Factory

The FallbackHeaders factory allows you to add Hystrix execution exception details in headers of a request forwarded to a fallbackUri in an external application, like in the following scenario:

FallbackHeaders工厂允许您在转发给外部应用程序fallbackUri的请求的头文件中添加Hystrix执行异常细节,如下面的场景所示:

application.yml

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

In this example, after an execution exception occurs while running the HystrixCommand, the request will be forwarded to the fallback endpoint or handler in an app running on localhost:9994. The headers with the exception type, message and -if available- root cause exception type and message will be added to that request by the FallbackHeaders filter.

在本例中,在运行HystrixCommand时发生执行异常后,请求将被转发到运行在localhost:9994上的应用程序中的回退端点或处理程序。包含异常类型、消息和(如果可用)根原因异常类型和消息的头将由FallbackHeaders过滤器添加到该请求中

The names of the headers can be overwritten in the config by setting the values of the arguments listed below, along with their default values:

通过设置下面列出的参数值及其默认值,可以在配置中覆盖头文件的名称

You can find more information on how Hystrix works with Gateway in the Hystrix GatewayFilter Factory section.

PrefixPath GatewayFilter Factory

The PrefixPath GatewayFilter Factory takes a single prefix parameter.

前缀路径网关过滤器工厂只接受一个前缀参数。

application.yml

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

This will prefix /mypath to the path of all matching requests. So a request to /hello, would be sent to /mypath/hello.

这将前缀/mypath到所有匹配请求的路径。因此,对/hello的请求将被发送到/mypath/hello

PreserveHostHeader GatewayFilter Factory

The PreserveHostHeader GatewayFilter Factory has no parameters. This filter sets a request attribute that the routing filter will inspect to determine if the original host header should be sent, rather than the host header determined by the http client.

PreserveHostHeader GatewayFilter Factory没有参数。 此过滤器设置路由过滤器将检查的请求属性,以确定是否应发送原始主机头,而不是http客户端确定的主机头。

application.yml

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

RequestRateLimiter GatewayFilter Factory

The RequestRateLimiter GatewayFilter Factory is uses a RateLimiter implementation to determine if the current request is allowed to proceed. If it is not, a status of HTTP 429 - Too Many Requests (by default) is returned.

RequestRateLimiter GatewayFilter Factory使用一个RateLimiter实现来确定是否允许当前请求继续进行。如果不是,则返回HTTP 429的状态—返回太多请求(默认情况下)

This filter takes an optional keyResolver parameter and parameters specific to the rate limiter (see below).

这个过滤器接受一个可选的keyResolver参数和特定于速率限制器的参数

keyResolver is a bean that implements the KeyResolver interface. In configuration, reference the bean by name using SpEL. #{@myKeyResolver} is a SpEL expression referencing a bean with the name myKeyResolver.

KeyResolver的默认实现是PrincipalNameKeyResolver,它从ServerWebExchange检索主体并调用Principal. getname()。

KeyResolver.java

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

The KeyResolver interface allows pluggable strategies to derive the key for limiting requests. In future milestones, there will be some KeyResolver implementations.

The default implementation of KeyResolver is the PrincipalNameKeyResolver which retrieves the Principal from the ServerWebExchange and calls Principal.getName().

By default, if the KeyResolver does not find a key, requests will be denied. This behavior can be adjusted with the spring.cloud.gateway.filter.request-rate-limiter.deny-empty-key (true or false) and spring.cloud.gateway.filter.request-rate-limiter.empty-key-status-code properties.

|   | The RequestRateLimiter is not configurable via the "shortcut" notation. The example below is invalid |

application.properties

# INVALID SHORTCUT CONFIGURATION spring.cloud.gateway.routes[0].filters[0]=RequestRateLimiter=2, 2, #{@userkeyresolver}

Redis RateLimiter

The redis implementation is based off of work done at Stripe. It requires the use of the spring-boot-starter-data-redis-reactiveSpring Boot starter.

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

The algorithm used is the Token Bucket Algorithm.

The redis-rate-limiter.replenishRate is how many requests per second do you want a user to be allowed to do, without any dropped requests. This is the rate that the token bucket is filled.

redis-rate-limiter.replenishRate是您希望允许用户每秒执行多少请求,而不会丢弃任何请求。 这是令牌桶填充的速率

The redis-rate-limiter.burstCapacity is the maximum number of requests a user is allowed to do in a single second. This is the number of tokens the token bucket can hold. Setting this value to zero will block all requests.

redis-rate-limiter.burstCapacity是用户在一秒钟内允许执行的最大请求数。 这是令牌桶可以容纳的令牌数。 将此值设置为零将阻止所有请求。

A steady rate is accomplished by setting the same value in replenishRate and burstCapacity. Temporary bursts can be allowed by setting burstCapacity higher than replenishRate. In this case, the rate limiter needs to be allowed some time between bursts (according to replenishRate), as 2 consecutive bursts will result in dropped requests (HTTP 429 - Too Many Requests).

通过在replenishRate和burstCapacity中设置相同的值来实现稳定的速率。 通过将burstCapacity设置为高于replenishRate,可以允许临时突发。 在这种情况下,需要在突发之间允许速率限制器一段时间(根据replenishRate),因为连续2次突发将导致请求被丢弃(HTTP 429  -  Too Many Requests)。

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

Config.java

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

This defines a request rate limit of 10 per user. A burst of 20 is allowed, but the next second only 10 requests will be available. The KeyResolver is a simple one that gets the user request parameter (note: this is not recommended for production).

这定义了每个用户10的请求率限制。 允许突发20,但下一秒只有10个请求可用。 KeyResolver是一个简单的获取用户请求参数(注意:这不建议用于生产)。

A rate limiter can also be defined as a bean implementing the RateLimiter interface. In configuration, reference the bean by name using SpEL. #{@myRateLimiter} is a SpEL expression referencing a bean with the name myRateLimiter.

速率限制器也可以定义为实现RateLimiter接口的bean。 在配置中,使用SpEL按名称引用bean。 #{@ myRateLimiter}是一个引用名为myRateLimiter的bean的SpEL表达式。

application.yml

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

RedirectTo GatewayFilter Factory

The RedirectTo GatewayFilter Factory takes a status and a url parameter. The status should be a 300 series redirect http code, such as 301. The url should be a valid url. This will be the value of the Location header.

RedirectTo GatewayFilter Factory采用status和url参数。 状态应该是300系列重定向http代码,例如301. url应该是有效的URL。 这将是Location标头的值。

application.yml

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

This will send a status 302 with a Location:https://acme.org header to perform a redirect.

RemoveHopByHopHeadersFilter GatewayFilter Factory

The RemoveHopByHopHeadersFilter GatewayFilter Factory removes headers from forwarded requests. The default list of headers that is removed comes from the IETF.

RemoveHopByHopHeadersFilter GatewayFilter Factory从转发的请求中删除标头。 删除的标头列表来自IETF。

The default removed headers are:

To change this, set the spring.cloud.gateway.filter.remove-non-proxy-headers.headers property to the list of header names to remove.

要更改此设置,请将spring.cloud.gateway.filter.remove-non-proxy-headers.headers属性设置为要删除的标头名称列表。

RemoveRequestHeader GatewayFilter Factory

The RemoveRequestHeader GatewayFilter Factory takes a name parameter. It is the name of the header to be removed.

RemoveRequestHeader GatewayFilter Factory采用名称参数。 它是要删除的标头的名称。

application.yml

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

This will remove the X-Request-Foo header before it is sent downstream.

RemoveResponseHeader GatewayFilter Factory

The RemoveResponseHeader GatewayFilter Factory takes a name parameter. It is the name of the header to be removed.

RemoveResponseHeader GatewayFilter Factory采用名称参数。 它是要删除的标头的名称。

application.yml

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

This will remove the X-Response-Foo header from the response before it is returned to the gateway client.

这将在响应返回到网关客户端之前从响应中删除X-Response-Foo标头

To remove any kind of sensitive header you should configure this filter for any routes that you may want to do so. In addition you can configure this filter once using spring.cloud.gateway.default-filters and have it applied to all routes.

要删除任何类型的敏感标头,您应该为您可能要执行此操作的任何路由配置此过滤器。 此外,您可以使用spring.cloud.gateway.default-filters配置此过滤器一次,并将其应用于所有路由。

RewritePath GatewayFilter Factory

The RewritePath GatewayFilter Factory takes a path regexp parameter and a replacement parameter. This uses Java regular expressions for a flexible way to rewrite the request path.

RewritePath GatewayFilter Factory采用路径regexp参数和替换参数。 这使用Java正则表达式来灵活地重写请求路径。

application.yml

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

For a request path of /foo/bar, this will set the path to /bar before making the downstream request. Notice the $\ which is replaced with $ because of the YAML spec.

对于/ foo / bar的请求路径,这将在发出下游请求之前将路径设置为/ bar。 注意由于YAML规范,$ \替换为$。

RewriteResponseHeader GatewayFilter Factory

The RewriteResponseHeader GatewayFilter Factory takes nameregexp, and replacement parameters. It uses Java regular expressions for a flexible way to rewrite the response header value.

RewriteResponseHeader GatewayFilter Factory采用名称,正则表达式和替换参数。 它使用Java正则表达式以灵活的方式重写响应头值。

application.yml

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

For a header value of /42?user=ford&password=omg!what&flag=true, it will be set to /42?user=ford&password=***&flag=true after making the downstream request. Please use $\ to mean $ because of the YAML spec.

SaveSession GatewayFilter Factory

The SaveSession GatewayFilter Factory forces a WebSession::save operation before forwarding the call downstream. This is of particular use when using something like Spring Session with a lazy data store and need to ensure the session state has been saved before making the forwarded call.

SaveSession GatewayFilter Factory在转发下游调用之前强制执行WebSession :: save操作。 当使用Spring Session与惰性数据存储之类的东西时,这是特别有用的,并且需要确保在转发调用之前已保存会话状态。

application.yml

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

If you are integrating Spring Security with Spring Session, and want to ensure security details have been forwarded to the remote process, this is critical.

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

SecureHeaders GatewayFilter Factory

The SecureHeaders GatewayFilter Factory adds a number of headers to the response at the recommendation from this blog post.

SecureHeaders GatewayFilter Factory根据此博客文章的建议为响应添加了许多标头。

The following headers are added (along with default values):

To change the default values set the appropriate property in the spring.cloud.gateway.filter.secure-headers namespace:

Property to change:

To disable the default values set the property spring.cloud.gateway.filter.secure-headers.disable with comma separated values.

Example:

spring.cloud.gateway.filter.secure-headers.disable=frame-options,download-options

SetPath GatewayFilter Factory

The SetPath GatewayFilter Factory takes a path template parameter. It offers a simple way to manipulate the request path by allowing templated segments of the path. This uses the uri templates from Spring Framework. Multiple matching segments are allowed.

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

application.yml

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

For a request path of /foo/bar, this will set the path to /bar before making the downstream request.

对于/ foo / bar的请求路径,这将在发出下游请求之前将路径设置为/ bar。

SetResponseHeader GatewayFilter Factory

The SetResponseHeader GatewayFilter Factory takes name and value parameters.

application.yml

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

This GatewayFilter replaces all headers with the given name, rather than adding. So if the downstream server responded with a X-Response-Foo:1234, this would be replaced with X-Response-Foo:Bar, which is what the gateway client would receive.

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

SetStatus GatewayFilter Factory

The SetStatus GatewayFilter Factory takes a single status parameter. It must be a valid Spring HttpStatus. It may be the integer value 404 or the string representation of the enumeration NOT_FOUND.

SetStatus GatewayFilter Factory采用单个状态参数。 它必须是有效的Spring HttpStatus。 它可以是整数值404或枚举NOT_FOUND的字符串表示形式。

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

In either case, the HTTP status of the response will be set to 401.

在这两种情况下,响应的HTTP状态都将设置为401

StripPrefix GatewayFilter Factory

The StripPrefix GatewayFilter Factory takes one parameter, parts. The parts parameter indicated the number of parts in the path to strip from the request before sending it downstream.

StripPrefix GatewayFilter Factory采用一个参数,即部件。 parts参数指示在向下游发送之前从请求中剥离的路径中的部分数。

application.yml

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

When a request is made through the gateway to /name/bar/foo the request made to nameservice will look like [https://nameservice/foo](https://nameservice/foo).

Retry GatewayFilter Factory

The Retry GatewayFilter Factory takes retriesstatusesmethods, and series as parameters.

Retry GatewayFilter Factory将重试,状态,方法和系列作为参数。

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

|   | The retry filter does not currently support retrying with a body (e.g. for POST or PUT requests with a body). |

重试过滤器目前不支持对主体进行重试(例如,对于使用主体的POST或PUT请求)。

|   | When using the retry filter with a forward: prefixed URL, the target endpoint should be written carefully so that in case of an error it does not do anything that could result in a response being sent to the client and committed. For example, if the target endpoint is an annotated controller, the target controller method should not return ResponseEntity with an error status code. Instead it should throw an Exception, or signal an error, e.g. via a Mono.error(ex) return value, which the retry filter can be configured to handle by retrying. |

RequestSize GatewayFilter Factory

The RequestSize GatewayFilter Factory can restrict a request from reaching the downstream service , when the request size is greater than the permissible limit. The filter takes RequestSize as parameter which is the permissible size limit of the request defined in bytes.

当请求大小大于允许的限制时,RequestSize GatewayFilter Factory可以限制请求到达下游服务。 过滤器将RequestSize作为参数,该参数是以字节为单位定义的请求的允许大小限制。

application.yml

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

The RequestSize GatewayFilter Factory set the response status as 413 Payload Too Large with a additional header errorMessagewhen the Request is rejected due to size. Following is an example of such an errorMessage .

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

|   | The default Request size will be set to 5 MB if not provided as filter argument in route definition. |

Modify Request Body GatewayFilter Factory

This filter is considered BETA and the API may change in the future

This filter can be used to modify the request body before it is sent downstream by the Gateway.

|   | This filter can only be configured using the 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;
    }
}

Modify Response Body GatewayFilter Factory

This filter is considered BETA and the API may change in the future

This filter can be used to modify the response body before it is sent back to the Client.

|   | This filter can only be configured using the 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();
}

Default Filters

If you would like to add a filter and apply it to all routes you can use spring.cloud.gateway.default-filters. This property takes a list of filters

如果您想添加过滤器并将其应用于所有路线,可以使用spring.cloud.gateway.default-filters。 此属性采用过滤器列表

application.yml

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

Global Filters

The GlobalFilter interface has the same signature as GatewayFilter. These are special filters that are conditionally applied to all routes. (This interface and usage are subject to change in future milestones).

GlobalFilter接口与GatewayFilter具有相同的签名。 这些是有条件地应用于所有路线的特殊过滤器

Combined Global Filter and GatewayFilter Ordering

When a request comes in (and matches a Route) the Filtering Web Handler will add all instances of GlobalFilter and all route specific instances of GatewayFilter to a filter chain. This combined filter chain is sorted by the org.springframework.core.Orderedinterface, which can be set by implementing the getOrder() method or by using the [@Order](https://my.oschina.net/u/212650) annotation.

As Spring Cloud Gateway distinguishes between "pre" and "post" phases for filter logic execution (see: How It Works), the filter with the highest precedence will be the first in the "pre"-phase and the last in the "post"-phase.

ExampleConfiguration.java

@Bean
@Order(-1)
public GlobalFilter a() {
    return (exchange, chain) -> {
        log.info("first pre filter");
        return chain.filter(exchange).then(Mono.fromRunnable(() -> {
            log.info("third post filter");
        }));
    };
}

@Bean
@Order(0)
public GlobalFilter b() {
    return (exchange, chain) -> {
        log.info("second pre filter");
        return chain.filter(exchange).then(Mono.fromRunnable(() -> {
            log.info("second post filter");
        }));
    };
}

@Bean
@Order(1)
public GlobalFilter c() {
    return (exchange, chain) -> {
        log.info("third pre filter");
        return chain.filter(exchange).then(Mono.fromRunnable(() -> {
            log.info("first post filter");
        }));
    };
}

Forward Routing Filter

The ForwardRoutingFilter looks for a URI in the exchange attribute ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR. If the url has a forward scheme (ie forward:///localendpoint), it will use the Spring DispatcherHandler to handler the request. The path part of the request URL will be 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.

ForwardRoutingFilter在交换属性ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR中查找URI。 如果url具有forward方案(即forward:/// localendpoint),它将使用Spring DispatcherHandler处理请求。 请求URL的路径部分将被转发URL中的路径覆盖。 未修改的原始URL将附加到ServerWebExchangeUtils.GATEWAY_ORIGINAL_REQUEST_URL_ATTR属性中的列表中。

LoadBalancerClient Filter

The LoadBalancerClientFilter looks for a URI in the exchange attribute ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR. If the url has a lb scheme (ie lb://myservice), it will use the Spring Cloud LoadBalancerClient to resolve the name (myservice in the previous example) to an actual host and port and replace the URI in the same attribute. The unmodified original url is appended to the list in the ServerWebExchangeUtils.GATEWAY_ORIGINAL_REQUEST_URL_ATTR attribute. The filter will also look in the ServerWebExchangeUtils.GATEWAY_SCHEME_PREFIX_ATTR attribute to see if it equals lb and then the same rules apply.

LoadBalancerClientFilter在交换属性ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR中查找URI。 如果url具有lb方案(即lb:// myservice),它将使用Spring Cloud LoadBalancerClient将名称(前一示例中的myservice)解析为实际主机和端口,并替换相同属性中的URI。 未修改的原始URL将附加到ServerWebExchangeUtils.GATEWAY_ORIGINAL_REQUEST_URL_ATTR属性中的列表中。 过滤器还将查看ServerWebExchangeUtils.GATEWAY_SCHEME_PREFIX_ATTR属性以查看它是否等于lb,然后应用相同的规则。

application.yml

spring:
  cloud:
    gateway:
      routes:
      - id: myRoute
        uri: lb://service
        predicates:
        - Path=/service/**

|   | By default when a service instance cannot be found in the LoadBalancer a 503 will be returned. You can configure the Gateway to return a 404 by setting spring.cloud.gateway.loadbalancer.use404=true. |

|   | The isSecure value of the ServiceInstance returned from the LoadBalancer will override the scheme specified in the request made to the Gateway. For example, if the request comes into the Gateway over HTTPS but the ServiceInstance indicates it is not secure, then the downstream request will be made over HTTP. The opposite situation can also apply. However if GATEWAY_SCHEME_PREFIX_ATTR is specified for the route in the Gateway configuration, the prefix will be stripped and the resulting scheme from the route URL will override the ServiceInstance configuration. |

Netty Routing Filter

The Netty Routing Filter runs if the url located in the ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR exchange attribute has a http or https scheme. It uses the Netty HttpClient to make the downstream proxy request. The response is put in the ServerWebExchangeUtils.CLIENT_RESPONSE_ATTR exchange attribute for use in a later filter. (There is an experimental WebClientHttpRoutingFilter that performs the same function, but does not require netty)

Netty Write Response Filter

The NettyWriteResponseFilter runs if there is a Netty HttpClientResponse in the ServerWebExchangeUtils.CLIENT_RESPONSE_ATTRexchange attribute. It is run after all other filters have completed and writes the proxy response back to the gateway client response. (There is an experimental WebClientWriteResponseFilter that performs the same function, but does not require netty)

RouteToRequestUrl Filter

The RouteToRequestUrlFilter runs if there is a Route object in the ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR exchange attribute. It creates a new URI, based off of the request URI, but updated with the URI attribute of the Route object. The new URI is placed in the ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR exchange attribute`.

If the URI has a scheme prefix, such as lb🇼🇸//serviceid, the lb scheme is stripped from the URI and placed in the ServerWebExchangeUtils.GATEWAY_SCHEME_PREFIX_ATTR for use later in the filter chain.

Websocket Routing Filter

The Websocket Routing Filter runs if the url located in the ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR exchange attribute has a ws or wss scheme. It uses the Spring Web Socket infrastructure to forward the Websocket request downstream.

Websockets may be load-balanced by prefixing the URI with lb, such as lb🇼🇸//serviceid.

|   | If you are using SockJS as a fallback over normal http, you should configure a normal HTTP route as well as the Websocket Route. |

application.yml

spring:
  cloud:
    gateway:
      routes:
      # SockJS route
      - id: websocket_sockjs_route
        uri: http://localhost:3001
        predicates:
        - Path=/websocket/info/**
      # Normwal Websocket route
      - id: websocket_route
        uri: ws://localhost:3001
        predicates:
        - Path=/websocket/**

Gateway Metrics Filter

To enable Gateway Metrics add spring-boot-starter-actuator as a project dependency. Then, by default, the Gateway Metrics Filter runs as long as the property spring.cloud.gateway.metrics.enabled is not set to false. This filter adds a timer metric named "gateway.requests" with the following tags:

These metrics are then available to be scraped from /actuator/metrics/gateway.requests and can be easily integated with Prometheus to create a Grafana dashboard.

|   | To enable the pometheus endpoint add micrometer-registry-prometheus as a project dependency. |

Marking An Exchange As Routed

After the Gateway has routed a ServerWebExchange it will mark that exchange as "routed" by adding gatewayAlreadyRouted to the exchange attributes. Once a request has been marked as routed, other routing filters will not route the request again, essentially skipping the filter. There are convenience methods that you can use to mark an exchange as routed or check if an exchange has already been routed.

TLS / SSL

The Gateway can listen for requests on https by following the usual Spring server configuration. Example:

application.yml

server:
  ssl:
    enabled: true
    key-alias: scg
    key-store-password: scg1234
    key-store: classpath:scg-keystore.p12
    key-store-type: PKCS12

Gateway routes can be routed to both http and https backends. If routing to a https backend then the Gateway can be configured to trust all downstream certificates with the following configuration:

application.yml

spring:
  cloud:
    gateway:
      httpclient:
        ssl:
          useInsecureTrustManager: true

Using an insecure trust manager is not suitable for production. For a production deployment the Gateway can be configured with a set of known certificates that it can trust with the following configuration:

application.yml

spring:
  cloud:
    gateway:
      httpclient:
        ssl:
          trustedX509Certificates:
          - cert1.pem
          - cert2.pem

If the Spring Cloud Gateway is not provisioned with trusted certificates the default trust store is used (which can be overridden with system property javax.net.ssl.trustStore).

TLS Handshake

The Gateway maintains a client pool that it uses to route to backends. When communicating over https the client initiates a TLS handshake. A number of timeouts are associated with this handshake. These timeouts can be configured (defaults shown):

application.yml

spring:
  cloud:
    gateway:
      httpclient:
        ssl:
          handshake-timeout-millis: 10000
          close-notify-flush-timeout-millis: 3000
          close-notify-read-timeout-millis: 0

Configuration

Configuration for Spring Cloud Gateway is driven by a collection of `RouteDefinitionLocator`s.

RouteDefinitionLocator.java

public interface RouteDefinitionLocator {
	Flux<RouteDefinition> getRouteDefinitions();
}

By default, a PropertiesRouteDefinitionLocator loads properties using Spring Boot’s @ConfigurationProperties mechanism.

The configuration examples above all use a shortcut notation that uses positional arguments rather than named ones. The two examples below are equivalent:

application.yml

spring:
  cloud:
    gateway:
      routes:
      - id: setstatus_route
        uri: https://example.org
        filters:
        - name: SetStatus
          args:
            status: 401
      - id: setstatusshortcut_route
        uri: https://example.org
        filters:
        - SetStatus=401

For some usages of the gateway, properties will be adequate, but some production use cases will benefit from loading configuration from an external source, such as a database. Future milestone versions will have RouteDefinitionLocatorimplementations based off of Spring Data Repositories such as: Redis, MongoDB and Cassandra.

对于网关的一些用法,属性是足够的,但是一些生产用例将受益于从外部源(例如数据库)加载配置。 未来的里程碑版本将具有基于Spring Data Repositories的RouteDefinitionLocator实现,例如:Redis,MongoDB和Cassandra。

Fluent Java Routes API

To allow for simple configuration in Java, there is a fluent API defined in the RouteLocatorBuilder bean.

为了允许在Java中进行简单配置,在RouteLocatorBuilder bean中定义了一个流畅的API。

GatewaySampleApplication.java

// static imports from GatewayFilters and RoutePredicates
@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder builder, ThrottleGatewayFilterFactory throttle) {
    return builder.routes()
            .route(r -> r.host("**.abc.org").and().path("/image/png")
                .filters(f ->
                        f.addResponseHeader("X-TestHeader", "foobar"))
                .uri("http://httpbin.org:80")
            )
            .route(r -> r.path("/image/webp")
                .filters(f ->
                        f.addResponseHeader("X-AnotherHeader", "baz"))
                .uri("http://httpbin.org:80")
            )
            .route(r -> r.order(-1)
                .host("**.throttle.org").and().path("/get")
                .filters(f -> f.filter(throttle.apply(1,
                        1,
                        10,
                        TimeUnit.SECONDS)))
                .uri("http://httpbin.org:80")
            )
            .build();
}

This style also allows for more custom predicate assertions. The predicates defined by RouteDefinitionLocator beans are combined using logical and. By using the fluent Java API, you can use the and()or() and negate() operators on the Predicateclass.

DiscoveryClient Route Definition Locator

The Gateway can be configured to create routes based on services registered with a DiscoveryClient compatible service registry.

可以将网关配置为基于在DiscoveryClient兼容服务注册中心注册的服务来创建路由。

To enable this, set spring.cloud.gateway.discovery.locator.enabled=true and make sure a DiscoveryClient implementation is on the classpath and enabled (such as Netflix Eureka, Consul or Zookeeper).

要启用此功能,请设置spring.cloud.gateway.discovery.locator.enabled = true并确保DiscoveryClient实现位于类路径上并已启用(例如Netflix Eureka,Consul或Zookeeper)。

Configuring Predicates and Filters For DiscoveryClient Routes

By default the Gateway defines a single predicate and filter for routes created via a DiscoveryClient.

The default predicate is a path predicate defined with the pattern /serviceId/**, where serviceId is the id of the service from the DiscoveryClient.

The default filter is rewrite path filter with the regex /serviceId/(?<remaining>.*) and the replacement /${remaining}. This just strips the service id from the path before the request is sent downstream.

If you would like to customize the predicates and/or filters used by the DiscoveryClient routes you can do so by setting spring.cloud.gateway.discovery.locator.predicates[x] and spring.cloud.gateway.discovery.locator.filters[y]. When doing so you need to make sure to include the default predicate and filter above, if you want to retain that functionality. Below is an example of what this looks like.

application.properties

spring.cloud.gateway.discovery.locator.predicates[0].name: Path spring.cloud.gateway.discovery.locator.predicates[0].args[pattern]: "'/'+serviceId+'/'" spring.cloud.gateway.discovery.locator.predicates[1].name: Host spring.cloud.gateway.discovery.locator.predicates[1].args[pattern]: "'.foo.com'" spring.cloud.gateway.discovery.locator.filters[0].name: Hystrix spring.cloud.gateway.discovery.locator.filters[0].args[name]: serviceId spring.cloud.gateway.discovery.locator.filters[1].name: RewritePath spring.cloud.gateway.discovery.locator.filters[1].args[regexp]: "'/' + serviceId + '/(?.*)'" spring.cloud.gateway.discovery.locator.filters[1].args[replacement]: "'/${remaining}'"

Reactor Netty Access Logs

To enable Reactor Netty access logs, set -Dreactor.netty.http.server.accessLogEnabled=true. (It must be a Java System Property, not a Spring Boot property).

The logging system can be configured to have a separate access log file. Below is an example logback configuration:

logback.xml

    <appender name="accessLog" class="ch.qos.logback.core.FileAppender">
        <file>access_log.log</file>
        <encoder>
            <pattern>%msg%n</pattern>
        </encoder>
    </appender>
    <appender name="async" class="ch.qos.logback.classic.AsyncAppender">
        <appender-ref ref="accessLog" />
    </appender>

    <logger name="reactor.netty.http.server.AccessLog" level="INFO" additivity="false">
        <appender-ref ref="async"/>
    </logger>

CORS Configuration

The gateway can be configured to control CORS behavior. The "global" CORS configuration is a map of URL patterns to Spring Framework CorsConfiguration.

application.yml

spring:
  cloud:
    gateway:
      globalcors:
        corsConfigurations:
          '[/**]':
            allowedOrigins: "https://docs.spring.io"
            allowedMethods:
            - GET

In the example above, CORS requests will be allowed from requests that originate from docs.spring.io for all GET requested paths.

Actuator API

The /gateway actuator endpoint allows to monitor and interact with a Spring Cloud Gateway application. To be remotely accessible, the endpoint has to be enabled and exposed via HTTP or JMX in the application properties.

application.properties

management.endpoint.gateway.enabled=true # default value
management.endpoints.web.exposure.include=gateway

Retrieving route filters

Global Filters

To retrieve the global filters applied to all routes, make a GET request to /actuator/gateway/globalfilters. The resulting response is similar to the following:

{ "org.springframework.cloud.gateway.filter.LoadBalancerClientFilter@77856cc5": 10100, "org.springframework.cloud.gateway.filter.RouteToRequestUrlFilter@4f6fd101": 10000, "org.springframework.cloud.gateway.filter.NettyWriteResponseFilter@32d22650": -1, "org.springframework.cloud.gateway.filter.ForwardRoutingFilter@106459d9": 2147483647, "org.springframework.cloud.gateway.filter.NettyRoutingFilter@1fbd5e0": 2147483647, "org.springframework.cloud.gateway.filter.ForwardPathFilter@33a71d23": 0, "org.springframework.cloud.gateway.filter.AdaptCachedBodyGlobalFilter@135064ea": 2147483637, "org.springframework.cloud.gateway.filter.WebsocketRoutingFilter@23c05889": 2147483646 }

The response contains details of the global filters in place. For each global filter is provided the string representation of the filter object (e.g., org.springframework.cloud.gateway.filter.LoadBalancerClientFilter@77856cc5) and the corresponding order in the filter chain.

Route Filters

To retrieve the GatewayFilter factories applied to routes, make a GET request to /actuator/gateway/routefilters. The resulting response is similar to the following:

{ "[AddRequestHeaderGatewayFilterFactory@570ed9c configClass = AbstractNameValueGatewayFilterFactory.NameValueConfig]": null, "[SecureHeadersGatewayFilterFactory@fceab5d configClass = Object]": null, "[SaveSessionGatewayFilterFactory@4449b273 configClass = Object]": null }

The response contains details of the GatewayFilter factories applied to any particular route. For each factory is provided the string representation of the corresponding object (e.g., [SecureHeadersGatewayFilterFactory@fceab5d configClass = Object]). Note that the null value is due to an incomplete implementation of the endpoint controller, for that it tries to set the order of the object in the filter chain, which does not apply to a GatewayFilter factory object.

Refreshing the route cache

To clear the routes cache, make a POST request to /actuator/gateway/refresh. The request returns a 200 without response body.

Retrieving the routes defined in the gateway

Retrieving the routes defined in the gateway - 检索网关中定义的路由

To retrieve the routes defined in the gateway, make a GET request to /actuator/gateway/routes. The resulting response is similar to the following:

[{ "route_id": "first_route", "route_object": { "predicate": "org.springframework.cloud.gateway.handler.predicate.PathRoutePredicateFactory$$Lambda$432/1736826640@1e9d7e7d", "filters": [ "OrderedGatewayFilter{delegate=org.springframework.cloud.gateway.filter.factory.PreserveHostHeaderGatewayFilterFactory$$Lambda$436/674480275@6631ef72, order=0}" ] }, "order": 0 }, { "route_id": "second_route", "route_object": { "predicate": "org.springframework.cloud.gateway.handler.predicate.PathRoutePredicateFactory$$Lambda$432/1736826640@cd8d298", "filters": [] }, "order": 0 }]

The response contains details of all the routes defined in the gateway. The following table describes the structure of each element (i.e., a route) of the response.

The GatewayFilter factories applied to the route.

Retrieving information about a particular route

To retrieve information about a single route, make a GET request to /actuator/gateway/routes/{id} (e.g., /actuator/gateway/routes/first_route). The resulting response is similar to the following:

{ "id": "first_route", "predicates": [{ "name": "Path", "args": {"_genkey_0":"/first"} }], "filters": [], "uri": "https://www.uri-destination.org", "order": 0 }]

The following table describes the structure of the response.

Creating and deleting a particular route

To create a route, make a POST request to /gateway/routes/{id_route_to_create} with a JSON body that specifies the fields of the route (see the previous subsection).

To delete a route, make a DELETE request to /gateway/routes/{id_route_to_delete}.

Recap: list of all endpoints

The table below summarises the Spring Cloud Gateway actuator endpoints. Note that each endpoint has /actuator/gateway as the base-path.

Developer Guide

TODO: overview of writing custom integrations

Writing Custom Route Predicate Factories

TODO: document writing Custom Route Predicate Factories

Writing Custom GatewayFilter Factories

In order to write a GatewayFilter you will need to implement GatewayFilterFactory. There is an abstract class called AbstractGatewayFilterFactory which you can extend.

PreGatewayFilterFactory.java

public class PreGatewayFilterFactory extends AbstractGatewayFilterFactory<PreGatewayFilterFactory.Config> {

	public PreGatewayFilterFactory() {
		super(Config.class);
	}

	@Override
	public GatewayFilter apply(Config config) {
		// grab configuration from Config object
		return (exchange, chain) -> {
            //If you want to build a "pre" filter you need to manipulate the
            //request before calling chain.filter
            ServerHttpRequest.Builder builder = exchange.getRequest().mutate();
            //use builder to manipulate the request
            return chain.filter(exchange.mutate().request(request).build());
		};
	}

	public static class Config {
        //Put the configuration properties for your filter here
	}

}

PostGatewayFilterFactory.java

public class PostGatewayFilterFactory extends AbstractGatewayFilterFactory<PostGatewayFilterFactory.Config> {

	public PostGatewayFilterFactory() {
		super(Config.class);
	}

	@Override
	public GatewayFilter apply(Config config) {
		// grab configuration from Config object
		return (exchange, chain) -> {
			return chain.filter(exchange).then(Mono.fromRunnable(() -> {
				ServerHttpResponse response = exchange.getResponse();
				//Manipulate the response in some way
			}));
		};
	}

	public static class Config {
        //Put the configuration properties for your filter here
	}

}

Writing Custom Global Filters

In order to write a custom global filter, you will need to implement GlobalFilter interface. This will apply the filter to all requests.

Example of how to set up a Global Pre and Post filter, respectively

@Bean
public GlobalFilter customGlobalFilter() {
    return (exchange, chain) -> exchange.getPrincipal()
        .map(Principal::getName)
        .defaultIfEmpty("Default User")
        .map(userName -> {
          //adds header to proxied request
          exchange.getRequest().mutate().header("CUSTOM-REQUEST-HEADER", userName).build();
          return exchange;
        })
        .flatMap(chain::filter);
}

@Bean
public GlobalFilter customGlobalPostFilter() {
    return (exchange, chain) -> chain.filter(exchange)
        .then(Mono.just(exchange))
        .map(serverWebExchange -> {
          //adds header to response
          serverWebExchange.getResponse().getHeaders().set("CUSTOM-RESPONSE-HEADER",
              HttpStatus.OK.equals(serverWebExchange.getResponse().getStatusCode()) ? "It worked": "It did not work");
          return serverWebExchange;
        })
        .then();
}

Writing Custom Route Locators and Writers

TODO: document writing Custom Route Locators and Writers

Building a Simple Gateway Using Spring MVC or Webflux

Spring Cloud Gateway provides a utility object called ProxyExchange which you can use inside a regular Spring web handler as a method parameter. It supports basic downstream HTTP exchanges via methods that mirror the HTTP verbs. With MVC it also supports forwarding to a local handler via the forward() method. To use the ProxyExchange just include the right module in your classpath (either spring-cloud-gateway-mvc or spring-cloud-gateway-webflux).

MVC example (proxying a request to "/test" downstream to a remote server):

@RestController
@SpringBootApplication
public class GatewaySampleApplication {

	@Value("${remote.home}")
	private URI home;

	@GetMapping("/test")
	public ResponseEntity<?> proxy(ProxyExchange<byte[]> proxy) throws Exception {
		return proxy.uri(home.toString() + "/image/png").get();
	}

}

The same thing with Webflux:

@RestController
@SpringBootApplication
public class GatewaySampleApplication {

	@Value("${remote.home}")
	private URI home;

	@GetMapping("/test")
	public Mono<ResponseEntity<?>> proxy(ProxyExchange<byte[]> proxy) throws Exception {
		return proxy.uri(home.toString() + "/image/png").get();
	}

}

There are convenience methods on the ProxyExchange to enable the handler method to discover and enhance the URI path of the incoming request. For example you might want to extract the trailing elements of a path to pass them downstream:

@GetMapping("/proxy/path/**")
public ResponseEntity<?> proxyPath(ProxyExchange<byte[]> proxy) throws Exception {
  String path = proxy.path("/proxy/path/");
  return proxy.uri(home.toString() + "/foos/" + path).get();
}

All the features of Spring MVC or Webflux are available to Gateway handler methods. So you can inject request headers and query parameters, for instance, and you can constrain the incoming requests with declarations in the mapping annotation. See the documentation for @RequestMapping in Spring MVC for more details of those features.

Headers can be added to the downstream response using the header() methods on ProxyExchange.

You can also manipulate response headers (and anything else you like in the response) by adding a mapper to the get() etc. method. The mapper is a Function that takes the incoming ResponseEntity and converts it to an outgoing one.

First class support is provided for "sensitive" headers ("cookie" and "authorization" by default) which are not passed downstream, and for "proxy" headers (x-forwarded-*).