+diff --git a/reference/html/index.html b/reference/html/index.html index 966c4cc1..881503c1 100644 --- a/reference/html/index.html +++ b/reference/html/index.html @@ -101,91 +101,91 @@ $(addBlockSwitches);
GatewayFilter Factories
AddRequestHeader GatewayFilter FactoryAddRequestParameter GatewayFilter FactoryAddResponseHeader GatewayFilter FactoryDedupeResponseHeader GatewayFilter FactoryGatewayFilter FactoryFallbackHeaders GatewayFilter FactoryMapRequestHeader GatewayFilter FactoryPrefixPath GatewayFilter FactoryPreserveHostHeader GatewayFilter FactoryRequestRateLimiter GatewayFilter Factory
RedirectTo GatewayFilter FactoryRemoveHopByHopHeadersFilter GatewayFilter FactoryRemoveRequestHeader GatewayFilter FactoryRemoveResponseHeader GatewayFilter FactoryRemoveRequestParameter GatewayFilter FactoryRewritePath GatewayFilter FactoryRewriteLocationResponseHeader GatewayFilter FactoryRewriteResponseHeader GatewayFilter FactorySaveSession GatewayFilter FactorySecureHeaders GatewayFilter FactorySetPath GatewayFilter FactorySetRequestHeader GatewayFilter FactorySetResponseHeader GatewayFilter FactorySetStatus GatewayFilter FactoryStripPrefix GatewayFilter FactoryGatewayFilter FactoryRequestSize GatewayFilter FactoryGatewayFilter FactoryGatewayFilter FactoryGatewayFilter OrderingLoadBalancerClient FilterReactiveLoadBalancerClientFilterRouteToRequestUrl FilterTo 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.
To include Spring Cloud Gateway in your project, use the starter with a group ID of org.springframework.cloud and an artifact ID of 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.
If you include the starter, but, for some reason, you do not want the gateway to be enabled, set spring.cloud.gateway.enabled=false.
If you include the starter, but you do not want the gateway to be enabled, set spring.cloud.gateway.enabled=false.
| -Spring Cloud Gateway is built upon Spring Boot 2.x, -Spring 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 is built on Spring Boot 2.x, Spring WebFlux, and Project Reactor. +As a consequence, many of the familiar synchronous libraries (Spring Data and Spring Security, for example) and patterns you know may not apply when you use 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. |
Route: Route the basic building block of the gateway. It is defined by an ID, a destination URI, a collection of predicates and a collection of filters. A route is matched if aggregate predicate is true.
+Route: The basic building block of the gateway. +It is defined by an ID, a destination URI, a collection of predicates, and a collection of filters. A route is matched if the aggregate predicate is true.
Predicate: This is a Java 8 Function Predicate. The input type is a Spring Framework ServerWebExchange. This allows developers to match on anything from the HTTP request, such as headers or parameters.
Predicate: This is a Java 8 Function Predicate. The input type is a Spring Framework ServerWebExchange.
+This lets you match on anything from the HTTP request, such as headers or parameters.
Filter: These are instances Spring Framework GatewayFilter constructed in with a specific factory. Here, requests and responses can be modified before or after sending the downstream request.
Filter: These are instances of Spring Framework GatewayFilter that have been constructed with a specific factory.
+Here, you can modify requests and responses before or after sending the downstream request.
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.
+The following diagram provides a high-level overview of how Spring Cloud Gateway works:
+
+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 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 can run logic both before and after the proxy request is sent. +All “pre” filter logic is executed. Then the proxy request is made. After the proxy request is made, the “post” filter logic is run.
| -URIs defined in routes without a port will get a default port set to 80 and 443 for HTTP and HTTPS URIs respectively. +URIs defined in routes without a port get default port values of 80 and 443 for the HTTP and HTTPS URIs, respectively. |
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 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.
+You can combine multiple route predicate factories with logical and statements.
The After Route Predicate Factory takes one parameter, a datetime. This predicate matches requests that happen after the current datetime.
+The after route predicate factory takes one parameter, a datetime. +This predicate matches requests that happen after the specified datetime. +The following example configures an after route predicate:
spring:
cloud:
@@ -343,17 +360,23 @@ URIs defined in routes without a port will get a default port set to 80 and 443
- 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).
+This route matches any request made after Jan 20, 2017 17:42 Mountain Time (Denver).
The Before Route Predicate Factory takes one parameter, a datetime. This predicate matches requests that happen before the current datetime.
+The before route predicate factory takes one parameter, a datetime.
+This predicate matches requests that happen before the specified datetime.
+The following example configures a before route predicate:
spring:
cloud:
@@ -365,17 +388,24 @@ URIs defined in routes without a port will get a default port set to 80 and 443
- 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).
+This route matches any request made before Jan 20, 2017 17:42 Mountain Time (Denver).
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.
+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.
+The following example configures a between route predicate:
spring:
cloud:
@@ -387,17 +417,24 @@ URIs defined in routes without a port will get a default port set to 80 and 443
- 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.
+This route matches any request made 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.
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.
+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 whose values match the regular expression. +The following example configures a cookie route predicate factory:
spring:
cloud:
@@ -409,17 +446,23 @@ URIs defined in routes without a port will get a default port set to 80 and 443
- Cookie=chocolate, ch.p
This route matches the request has a cookie named chocolate who’s value matches the ch.p regular expression.
This route matches requests that have a cookie named chocolate whose value matches the ch.p regular expression.
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.
+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 whose value matches the regular expression. +The following example configures a header route predicate:
spring:
cloud:
@@ -431,17 +474,24 @@ URIs defined in routes without a port will get a default port set to 80 and 443
- 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).
This route matches if the request has a header named X-Request-Id whose value matches the \d+ regular expression (that is, it has a value of one or more digits).
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.
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.
+The following example configures a host route predicate:
spring:
cloud:
@@ -453,23 +503,29 @@ URIs defined in routes without a port will get a default port set to 80 and 443
- 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.
URI template variables (such as {sub}.myhost.org) are supported as well.
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
This route matches if the request has a Host header with a value of www.somehost.org or beta.somehost.org or www.anotherhost.org.
This predicate extracts the URI template variables (such as sub, defined in the preceding example) 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
The Method Route Predicate Factory takes one or more parameters: the HTTP methods to match.
+The Method Route Predicate Factory takes one or more parameters: the HTTP methods to match. +The following example configures a method route predicate:
spring:
cloud:
@@ -481,17 +537,22 @@ URIs defined in routes without a port will get a default port set to 80 and 443
- Method=GET,POST
This route would match if the request method was a GET or a POST.
This route matches if the request method was a GET or a POST.
The Path Route Predicate Factory takes two parameters: a list of Spring PathMatcher patterns and an optional flag to matchOptionalTrailingSeparator.
The Path Route Predicate Factory takes two parameters: a list of Spring PathMatcher patterns and an optional flag called matchOptionalTrailingSeparator.
+The following example configures a path route predicate:
spring:
cloud:
@@ -500,18 +561,24 @@ URIs defined in routes without a port will get a default port set to 80 and 443
- id: host_route
uri: https://example.org
predicates:
- - Path=/foo/{segment},/bar/{segment}
+ - Path=/red/{segment},/blue/{segment}
+This route would match if the request path was, for example: /foo/1 or /foo/bar or /bar/baz.
This route matches if the request path was, for example: /red/1 or /red/blue or /blue/green.
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
This predicate extracts the URI template variables (such as segment, defined in the preceding example) 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.
+A utility method (called get) is available to make access to these variables easier.
+The following example shows how to use the get method:
Map<String, String> uriVariables = ServerWebExchangeUtils.getPathPredicateVariables(exchange);
@@ -520,10 +587,33 @@ String segment = uriVariables.get("segment");
The Query Route Predicate Factory takes two parameters: a required param and an optional regexp.
The query route predicate factory takes two parameters: a required param and an optional regexp.
+The following example configures a query route predicate:
spring:
+ cloud:
+ gateway:
+ routes:
+ - id: query_route
+ uri: https://example.org
+ predicates:
+ - Query=green
+The preceding route matches if the request contained a green query parameter.
This route would match if the request contained a baz query parameter.
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 baz would match.
The preceding route matches if the request contained a red query parameter whose value matched the gree. regexp, so green and greet would match.
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).
The RemoteAddr route predicate factory takes a list (min size 1) of CIDR-notation (IPv4 or IPv6) strings, such as 192.168.0.1/16 (where 192.168.0.1 is an IP address and 16 is a subnet mask).
+The following example configures a RemoteAddr route predicate:
spring:
cloud:
@@ -576,17 +653,22 @@ String segment = uriVariables.get("segment");
- RemoteAddr=192.168.1.1/24
This route would match if the remote address of the request was, for example, 192.168.1.10.
This route matches if the remote address of the request was, for example, 192.168.1.10.
The Weight Route Predicate Factory takes two argument group and weight. The weights are calculated per group.
+The weight route predicate factory takes two arguments: group and weight. The weights are calculated per group. +The following example configures a weight route predicate:
spring:
cloud:
@@ -602,41 +684,51 @@ String segment = uriVariables.get("segment");
- Weight=group1, 2
This route would forward ~80% of traffic to weighthigh.org and ~20% of traffic to weighlow.org
By default the RemoteAddr Route Predicate Factory uses the remote address from the incoming request. +
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.
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.
XForwardedRemoteAddressResolver.
XForwardedRemoteAddressResolver has two static constructor methods which take different approaches to security:
XForwardedRemoteAddressResolver has two static constructor methods, which take different approaches to security:
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.
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.
+
XForwardedRemoteAddressResolver::trustAll returns a RemoteAddressResolver that 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.
XForwardedRemoteAddressResolver::maxTrustedIndex takes an index that correlates to the number of trusted infrastructure running in front of Spring Cloud Gateway.
+If Spring Cloud Gateway is, for example only accessible through 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:
+Consider 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.
The following maxTrustedIndex values yield the following remote addresses:
Using Java config:
-GatewayConfig.java
+The following example shows how to achieve the same configuration with Java:
RemoteAddressResolver resolver = XForwardedRemoteAddressResolver
@@ -689,7 +781,7 @@ If two hops of trusted infrastructure are required before Spring Cloud Gateway i
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")
+ r -> r.remoteAddr(resolver, "10.10.1.1", "10.10.1.1/24")
.uri("https://downstream2")
)
GatewayFilter FactoriesRoute 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.
+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.
NOTE For more detailed examples on how to use any of the following filters, take a look at the unit tests.
+| + + | ++For more detailed examples of how to use any of the following filters, take a look at the unit tests. + | +
AddRequestHeader GatewayFilter FactoryThe AddRequestHeader GatewayFilter Factory takes a name and value parameter.
+The AddRequestHeader GatewayFilter factory takes a name and value parameter.
+The following example configures an AddRequestHeader GatewayFilter:
spring:
cloud:
@@ -722,17 +830,23 @@ If two hops of trusted infrastructure are required before Spring Cloud Gateway i
- id: add_request_header_route
uri: https://example.org
filters:
- - AddRequestHeader=X-Request-Foo, Bar
+ - AddRequestHeader=X-Request-red, blue
+This will add X-Request-Foo:Bar header to the downstream request’s headers for all matching requests.
This listing adds X-Request-red:blue header to the downstream request’s headers for all matching requests.
AddRequestHeader is aware of URI variables used to match a path or host. URI variables may be used in the value and will be expanded at runtime.
+AddRequestHeader is aware of the URI variables used to match a path or host.
+URI variables may be used in the value and are expanded at runtime.
+The following example configures an AddRequestHeader GatewayFilter that uses a variable:
spring:
cloud:
@@ -741,19 +855,24 @@ If two hops of trusted infrastructure are required before Spring Cloud Gateway i
- id: add_request_header_route
uri: https://example.org
predicates:
- - Path=/foo/{segment}
+ - Path=/red/{segment}
filters:
- - AddRequestHeader=X-Request-Foo, Bar-{segment}
+ - AddRequestHeader=X-Request-Red, Blue-{segment}
+AddRequestParameter GatewayFilter FactoryThe AddRequestParameter GatewayFilter Factory takes a name and value parameter.
+The AddRequestParameter GatewayFilter Factory takes a name and value parameter.
+The following example configures an AddRequestParameter GatewayFilter:
spring:
cloud:
@@ -762,17 +881,23 @@ If two hops of trusted infrastructure are required before Spring Cloud Gateway i
- id: add_request_parameter_route
uri: https://example.org
filters:
- - AddRequestParameter=foo, bar
+ - AddRequestParameter=red, blue
+This will add foo=bar to the downstream request’s query string for all matching requests.
This will add red=blue to the downstream request’s query string for all matching requests.
AddRequestParameter is aware of URI variables used to match a path or host. URI variables may be used in the value and will be expanded at runtime.
+AddRequestParameter is aware of the URI variables used to match a path or host.
+URI variables may be used in the value and are expanded at runtime.
+The following example configures an AddRequestParameter GatewayFilter that uses a variable:
spring:
cloud:
@@ -787,13 +912,18 @@ If two hops of trusted infrastructure are required before Spring Cloud Gateway i
The AddResponseHeader GatewayFilter Factory takes a name and value parameter.
AddResponseHeader GatewayFilter FactoryThe AddResponseHeader GatewayFilter Factory takes a name and value parameter.
+The following example configures an AddResponseHeader GatewayFilter:
spring:
cloud:
@@ -802,17 +932,23 @@ If two hops of trusted infrastructure are required before Spring Cloud Gateway i
- id: add_response_header_route
uri: https://example.org
filters:
- - AddResponseHeader=X-Response-Foo, Bar
+ - AddResponseHeader=X-Response-Red, Blue
+This will add X-Response-Foo:Bar header to the downstream response’s headers for all matching requests.
This adds X-Response-Foo:Bar header to the downstream response’s headers for all matching requests.
AddResponseHeader is aware of URI variables used to match a path or host. URI variables may be used in the value and will be expanded at runtime.
+AddResponseHeader is aware of URI variables used to match a path or host.
+URI variables may be used in the value and are expanded at runtime.
+The following example configures an AddResponseHeader GatewayFilter that uses a variable:
spring:
cloud:
@@ -827,13 +963,18 @@ If two hops of trusted infrastructure are required before Spring Cloud Gateway i
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 FactoryThe DedupeResponseHeader GatewayFilter factory takes a name parameter and an optional strategy parameter. name can contain a space-separated list of header names.
+The following example configures a DedupeResponseHeader GatewayFilter:
spring:
cloud:
@@ -845,15 +986,18 @@ If two hops of trusted infrastructure are required before Spring Cloud Gateway i
- 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.
The DedupeResponseHeader filter also accepts an optional strategy parameter. The accepted values are RETAIN_FIRST (default), RETAIN_LAST, and RETAIN_UNIQUE.
This removes 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 logic add them.
The DedupeResponseHeader filter also accepts an optional strategy parameter.
+The accepted values are RETAIN_FIRST (default), RETAIN_LAST, and RETAIN_UNIQUE.
GatewayFilter Factory| -Netflix has put Hystrix in maintenance mode. It is suggested you use the Spring Cloud CircuitBreaker -Gateway Filter with Resilience4J as support for Hystrix will be removed in a future release. +Netflix has put Hystrix in maintenance mode. We suggest you use the Spring Cloud CircuitBreaker +Gateway Filter with Resilience4J, as support for Hystrix will be removed in a future release. |
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.
+The HystrixGatewayFilter lets you introduce circuit breakers to your gateway routes, protecting your services from cascading failures and letting you 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.
To enable Hystrix GatewayFilter instances 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.
The Hystrix GatewayFilter factory requires a single name parameter, which is the name of the HystrixCommand.
+The following example configures a Hystrix GatewayFilter:
spring:
cloud:
@@ -890,14 +1037,19 @@ The Hystrix GatewayFilter allows you to introduce circuit breakers to your gatew
- 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.
This wraps the remaining filters in a HystrixCommand with a command name of 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 is forwarded to the controller matched by the URI.
+The following example configures such a fallback:
spring:
cloud:
@@ -915,15 +1067,19 @@ The Hystrix GatewayFilter allows you to introduce circuit breakers to your gatew
- 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.
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 (defined the lb prefix on the destination URI).
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:
spring:
cloud:
@@ -944,46 +1100,52 @@ However, it is also possible to reroute the request to a controller or handler i
- 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 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.
In this example, there is no fallback endpoint or handler in the gateway application.
+However, there is one in another application, registered under localhost:9994.
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.
+In case of the request being forwarded to the fallback, the Hystrix Gateway filter also provides the Throwable that has caused it.
+It is added to the ServerWebExchange as the ServerWebExchangeUtils.HYSTRIX_EXECUTION_EXCEPTION_ATTR attribute, which you can use when handling the fallback within the gateway application.
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.
+For the external controller/handler scenario, you can add headers with exception details. +You can find more information on doing so in the FallbackHeaders GatewayFilter Factory section.
To set a 5 second timeout for the example route above, the following configuration would be used:
+You can configured Hystrix settings (such as timeouts) with global defaults or on a route-by-route basis by using application properties, as explained on the Hystrix wiki.
To set a five-second timeout for the example route shown earlier, you could use the following configuration:
+hystrix.command.fallbackcmd.execution.isolation.thread.timeoutInMilliseconds: 5000
The Spring Cloud CircuitBreaker filter factory leverages the Spring Cloud CircuitBreaker APIs to wrap Gateway routes in -a circuit breaker. Spring Cloud CircuitBreaker supports two libraries which can be used with Spring Cloud Gateway, Hystrix -and Resilience4J. Since Netflix has places Hystrix in maintenance only mode we suggest you use Resilience4J.
+The Spring Cloud CircuitBreaker GatewayFilter factory uses the Spring Cloud CircuitBreaker APIs to wrap Gateway routes in +a circuit breaker. Spring Cloud CircuitBreaker supports two libraries that can be used with Spring Cloud Gateway, Hystrix +and Resilience4J. Since Netflix has placed Hystrix in maintenance-only mode, we suggest that you use Resilience4J.
To enable the Spring Cloud CircuitBreaker filter you will need to either place spring-cloud-starter-circuitbreaker-reactor-resilience4j or
-spring-cloud-starter-netflix-hystrix on the classpath.
To enable the Spring Cloud CircuitBreaker filter, you need to place either spring-cloud-starter-circuitbreaker-reactor-resilience4j or spring-cloud-starter-netflix-hystrix on the classpath.
+The following example configures a Spring Cloud CircuitBreaker GatewayFilter:
spring:
cloud:
@@ -995,6 +1157,8 @@ and Resilience4J. Since Netflix has places Hystrix in maintenance only mode we
- CircuitBreaker=myCircuitBreaker
To configure the circuit breaker, see the configuration for the underlying circuit breaker implementation you are using.
The Spring Cloud CircuitBreaker 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.
The Spring Cloud CircuitBreaker filter can also accept an optional fallbackUri parameter.
+Currently, only forward: schemed URIs are supported.
+If the fallback is called, the request is forwarded to the controller matched by the URI.
+The following example configures such a fallback:
spring:
cloud:
@@ -1030,8 +1199,15 @@ and Resilience4J. Since Netflix has places Hystrix in maintenance only mode we
- RewritePath=/consumingServiceEndpoint, /backingServiceEndpoint
The following listing does the same thing in Java:
+@Bean
public RouteLocator routes(RouteLocatorBuilder builder) {
@@ -1043,15 +1219,20 @@ public RouteLocator routes(RouteLocatorBuilder builder) {
}
This will forward to the /inCaseofFailureUseThis URI when the circuit breaker fallback is called. Note that this example also demonstrates (optional) Spring Cloud Netflix Ribbon load-balancing via the lb prefix on the destination URI.
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:
This example forwards to the /inCaseofFailureUseThis URI when the circuit breaker fallback is called.
+Note that this example also demonstrates the (optional) Spring Cloud Netflix Ribbon load-balancing (defined by the lb prefix on the destination URI).
The primary scenario is to use the fallbackUri to define an internal controller or handler within the gateway application.
+However, you can also reroute the request to a controller or handler in an external application, as follows:
spring:
cloud:
@@ -1072,29 +1253,30 @@ However, it is also possible to reroute the request to a controller or handler i
- 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 localhost:9994.
In case of the request being forwarded to fallback, the Spring Cloud CircuitBreaker Gateway filter also provides the Throwable that has
-caused it. It’s added to the ServerWebExchange as the
-ServerWebExchangeUtils.CIRCUITBREAKER_EXECUTION_EXCEPTION_ATTR attribute that can be used when
-handling the fallback within the gateway app.
In this example, there is no fallback endpoint or handler in the gateway application.
+However, there is one in another application, registered under localhost:9994.
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.
+In case of the request being forwarded to fallback, the Spring Cloud CircuitBreaker Gateway filter also provides the Throwable that has caused it.
+It is added to the ServerWebExchange as the ServerWebExchangeUtils.CIRCUITBREAKER_EXECUTION_EXCEPTION_ATTR attribute that can be used when handling the fallback within the gateway application.
For the external controller/handler scenario, headers can be added with exception details. +You can find more information on doing so in the FallbackHeaders GatewayFilter Factory section.
FallbackHeaders GatewayFilter FactoryThe FallbackHeaders factory allows you to add Hystrix or Spring Cloud CircuitBreaker execution exception details in headers of a request forwarded to
-a fallbackUri in an external application, like in the following scenario:
The FallbackHeaders factory lets you add Hystrix or Spring Cloud CircuitBreaker execution exception details in the headers of a request forwarded to a fallbackUri in an external application, as in the following scenario:
spring:
cloud:
@@ -1119,14 +1301,14 @@ a fallbackUri in an external application, like in the following sce
executionExceptionTypeHeaderName: Test-Header
In this example, after an execution exception occurs while running the circuit breaker, 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.
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:
+In this example, after an execution exception occurs while running the circuit breaker, the request is forwarded to the fallback endpoint or handler in an application running on localhost:9994.
+The headers with the exception type, message and (if available) root cause exception type and message are added to that request by the FallbackHeaders filter.
You can overwrite the names of the headers in the configuration by setting the values of the following arguments (shown with their default values):
For more information of circuit beakers and the Gateway see the Hystrix GatewayFilter Factory section or -Spring Cloud CircuitBreaker Factory section.
+For more information on circuit beakers and the gatewayc see the Hystrix GatewayFilter Factory section or Spring Cloud CircuitBreaker Factory section.
MapRequestHeader GatewayFilter FactoryThe MapRequestHeader GatewayFilter Factory takes 'fromHeader' and 'toHeader' parameters. It creates a new named header (toHeader) and the value is extracted out of an existing named header (fromHeader) from the incoming http request. If the input header does not exist then the filter has no impact. If the new named header already exists then it’s values will be augmented with the new values.
+The MapRequestHeader GatewayFilter factory takes fromHeader and toHeader parameters.
+It creates a new named header (toHeader), and the value is extracted out of an existing named header (fromHeader) from the incoming http request.
+If the input header does not exist, the filter has no impact.
+If the new named header already exists, its values are augmented with the new values.
+The following example configures a MapRequestHeader:
spring:
cloud:
@@ -1164,20 +1351,25 @@ their default values:
- id: map_request_header_route
uri: https://example.org
filters:
- - MapRequestHeader=Bar, X-Request-Foo
+ - MapRequestHeader=Blue, X-Request-Red
+This will add X-Request-Foo:<values> header to the downstream request’s with updated values from the incoming http request Bar header.
This adds X-Request-Red:<values> header to the downstream request with updated values from the incoming HTTP request’s Blue header.
PrefixPath GatewayFilter FactoryThe PrefixPath GatewayFilter Factory takes a single prefix parameter.
The PrefixPath GatewayFilter factory takes a single prefix parameter.
+The following example configures a PrefixPath GatewayFilter:
spring:
cloud:
@@ -1189,17 +1381,24 @@ their default values:
- PrefixPath=/mypath
This will prefix /mypath to the path of all matching requests. So a request to /hello, would be sent to /mypath/hello.
This will prefix /mypath to the path of all matching requests.
+So a request to /hello would be sent to /mypath/hello.
PreserveHostHeader GatewayFilter FactoryThe 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.
+The PreserveHostHeader GatewayFilter factory has no parameters.
+This filter sets a request attribute that the routing filter inspects to determine if the original host header should be sent, rather than the host header determined by the HTTP client.
+The following example configures a PreserveHostHeader GatewayFilter:
spring:
cloud:
@@ -1212,33 +1411,44 @@ their default values:
RequestRateLimiter GatewayFilter FactoryThe 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.
The RequestRateLimiter GatewayFilter factory 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.
This filter takes an optional keyResolver parameter and parameters specific to the rate limiter (see below).
This filter takes an optional keyResolver parameter and parameters specific to the rate limiter (described later in this section).
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 is a bean that implements the KeyResolver interface.
+In configuration, reference the bean by name using SpEL.
+#{@myKeyResolver} is a SpEL expression that references a bean named myKeyResolver.
+The following listing shows the KeyResolver interface:
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().
The KeyResolver interface lets pluggable strategies derive the key for limiting requests.
+In future milestone releases, there will be some KeyResolver implementations.
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 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 are denied.
+You can adjust this behavior by setting 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 - | - -
The RequestRateLimiter is not configurable with the "shortcut" notation. The following example below is invalid:
# INVALID SHORTCUT CONFIGURATION
spring.cloud.gateway.routes[0].filters[0]=RequestRateLimiter=2, 2, #{@userkeyresolver}
RateLimiterThe redis implementation is based off of work done at Stripe. It requires the use of the spring-boot-starter-data-redis-reactive Spring Boot starter.
The Redis implementation is based off of work done at Stripe.
+It requires the use of the spring-boot-starter-data-redis-reactive Spring Boot starter.
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.
The redis-rate-limiter.replenishRate is how many requests per second you want a user to be allowed to do, without any dropped requests.
+This is the rate at which the token bucket is filled.
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.
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 blocks all requests.
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).
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 two consecutive bursts will result in dropped requests (HTTP 429 - Too Many Requests).
+The following listing configures a redis-rate-limiter:
spring:
cloud:
@@ -1292,8 +1517,15 @@ spring.cloud.gateway.routes[0].filters[0]=RequestRateLimiter=2, 2, #{@userkeyres
redis-rate-limiter.burstCapacity: 20
The following example configures a KeyResolver in Java:
+@Bean
KeyResolver userKeyResolver() {
@@ -1301,14 +1533,22 @@ KeyResolver userKeyResolver() {
}
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).
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.
This defines a request rate limit of 10 per user. A burst of 20 is allowed, but, in the next second, only 10 requests are available.
+The KeyResolver is a simple one that gets the user request parameter (note that this is not recommended for production).
You can also define a rate limiter as a bean that implements the RateLimiter interface.
+In configuration, you can reference the bean by name using SpEL.
+#{@myRateLimiter} is a SpEL expression that references a bean with named myRateLimiter.
+The following listing defines a rate limiter that uses the KeyResolver defined in the previous listing:
spring:
cloud:
@@ -1325,13 +1565,21 @@ KeyResolver userKeyResolver() {
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 FactoryThe RedirectTo GatewayFilter factory takes two parameters, status and url.
+The status parameter should be a 300 series redirect HTTP code, such as 301.
+The url parameter should be a valid URL.
+This is the value of the Location header.
+The following listing configures a RedirectTo GatewayFilter:
spring:
cloud:
@@ -1343,55 +1591,62 @@ KeyResolver userKeyResolver() {
- RedirectTo=302, https://acme.org
This will send a status 302 with a Location:https://acme.org header to perform a redirect.
RemoveHopByHopHeadersFilter GatewayFilter FactoryThe RemoveHopByHopHeadersFilter GatewayFilter Factory removes headers from forwarded requests. The default list of headers that is removed comes from the IETF.
+The RemoveHopByHopHeadersFilter GatewayFilter Factory removes headers from forwarded requests.
+The default list of headers that is removed comes from the IETF.
Connection
+Connection
Keep-Alive
+Keep-Alive
Proxy-Authenticate
+Proxy-Authenticate
Proxy-Authorization
+Proxy-Authorization
TE
+TE
Trailer
+Trailer
Transfer-Encoding
+Transfer-Encoding
Upgrade
+Upgrade
To change this, set the spring.cloud.gateway.filter.remove-non-proxy-headers.headers property to the list of header names to remove.
To change the removed headers, set the spring.cloud.gateway.filter.remove-non-proxy-headers.headers property to the list of header names to remove.
RemoveRequestHeader GatewayFilter FactoryThe RemoveRequestHeader GatewayFilter Factory takes a name parameter. It is the name of the header to be removed.
The RemoveRequestHeader GatewayFilter factory takes a name parameter.
+It is the name of the header to be removed.
+The following listing configures a RemoveRequestHeader GatewayFilter:
spring:
cloud:
@@ -1403,17 +1658,23 @@ KeyResolver userKeyResolver() {
- RemoveRequestHeader=X-Request-Foo
This will remove the X-Request-Foo header before it is sent downstream.
This removes the X-Request-Foo header before it is sent downstream.
RemoveResponseHeader GatewayFilter FactoryThe RemoveResponseHeader GatewayFilter Factory takes a name parameter. It is the name of the header to be removed.
The RemoveResponseHeader GatewayFilter factory takes a name parameter.
+It is the name of the header to be removed.
+The following listing configures a RemoveResponseHeader GatewayFilter:
spring:
cloud:
@@ -1425,22 +1686,27 @@ KeyResolver userKeyResolver() {
- RemoveResponseHeader=X-Response-Foo
This will remove the X-Response-Foo header from the response before it is returned to the gateway client.
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.
To remove any kind of sensitive header, you should configure this filter for any routes for which you may want to do so.
+In addition, you can configure this filter once by using spring.cloud.gateway.default-filters and have it applied to all routes.
RemoveRequestParameter GatewayFilter FactoryThe RemoveRequestParameter GatewayFilter Factory takes a name parameter. It is the name of the query parameter to be removed.
The RemoveRequestParameter GatewayFilter factory takes a name parameter.
+It is the name of the query parameter to be removed.
+The following example configures a RemoveRequestParameter GatewayFilter:
spring:
cloud:
@@ -1449,20 +1715,26 @@ and have it applied to all routes.
- id: removerequestparameter_route
uri: https://example.org
filters:
- - RemoveRequestParameter=foo
+ - RemoveRequestParameter=red
+This will remove the foo parameter before it is sent downstream.
This will remove the red parameter before it is sent downstream.
RewritePath GatewayFilter FactoryThe 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.
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.
+The following listing configures a RewritePath GatewayFilter:
spring:
cloud:
@@ -1473,20 +1745,26 @@ and have it applied to all routes.
predicates:
- Path=/foo/**
filters:
- - RewritePath=/foo(?<segment>/?.*), $\{segment}
+ - RewritePath=/red(?<segment>/?.*), $\{segment}
+For a request path of /foo/bar, this will set the path to /bar before making the downstream request. Notice the $ Should be replaced with $\ because of the YAML spec.
For a request path of /red/blue, this sets the path to /blue before making the downstream request. Note that the $ should be replaced with $\ because of the YAML specification.
RewriteLocationResponseHeader GatewayFilter FactoryThe RewriteLocationResponseHeader GatewayFilter Factory modifies the value of Location response header, usually to get rid of backend specific details. It takes stripVersionMode, locationHeaderName, hostValue, and protocolsRegex parameters.
The RewriteLocationResponseHeader GatewayFilter factory modifies the value of the Location response header, usually to get rid of backend-specific details.
+It takes stripVersionMode, locationHeaderName, hostValue, and protocolsRegex parameters.
+The following listing configures a RewriteLocationResponseHeader GatewayFilter:
spring:
cloud:
@@ -1498,39 +1776,48 @@ and have it applied to all routes.
- RewriteLocationResponseHeader=AS_IN_REQUEST, Location, ,
For example, for a request POST api.example.com/some/object/name, Location response header value object-service.prod.example.net/v2/some/object/id will be rewritten as api.example.com/some/object/id.
Parameter stripVersionMode has the following possible values: NEVER_STRIP, AS_IN_REQUEST (default), ALWAYS_STRIP.
For example, for a request of POST api.example.com/some/object/name, the Location response header value of object-service.prod.example.net/v2/some/object/id is rewritten as api.example.com/some/object/id.
The stripVersionMode parameter has the following possible values: NEVER_STRIP, AS_IN_REQUEST (default), and ALWAYS_STRIP.
NEVER_STRIP - Version will not be stripped, even if the original request path contains no version
NEVER_STRIP: The version is not stripped, even if the original request path contains no version.
AS_IN_REQUEST - Version will be stripped only if the original request path contains no version
AS_IN_REQUEST The version is stripped only if the original request path contains no version.
ALWAYS_STRIP - Version will be stripped, even if the original request path contains version
ALWAYS_STRIP The version is always stripped, even if the original request path contains version.
Parameter hostValue, if provided, will be used to replace the host:port portion of the response Location header. If not provided, the value of the Host request header will be used.
The hostValue parameter, if provided, is used to replace the host:port portion of the response Location header.
+If it is not provided, the value of the Host request header is used.
Parameter protocolsRegex must be a valid regex String, against which the protocol name will be matched. If not matched, the filter will do nothing. Default is http|https|ftp|ftps.
The protocolsRegex parameter must be a valid regex String, against which the protocol name is matched.
+If it is not matched, the filter does nothing.
+The default is http|https|ftp|ftps.
RewriteResponseHeader GatewayFilter FactoryThe RewriteResponseHeader GatewayFilter Factory takes name, regexp, and replacement parameters. It uses Java regular expressions for a flexible way to rewrite the response header value.
The RewriteResponseHeader GatewayFilter factory takes name, regexp, and replacement parameters.
+It uses Java regular expressions for a flexible way to rewrite the response header value.
+The following example configures a RewriteResponseHeader GatewayFilter:
spring:
cloud:
@@ -1539,21 +1826,27 @@ and have it applied to all routes.
- id: rewriteresponseheader_route
uri: https://example.org
filters:
- - RewriteResponseHeader=X-Response-Foo, , password=[^&]+, password=***
+ - RewriteResponseHeader=X-Response-Red, , 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.
For a header value of /42?user=ford&password=omg!what&flag=true, it is set to /42?user=ford&password=***&flag=true after making the downstream request.
+You must use $\ to mean $ because of the YAML specification.
SaveSession GatewayFilter FactoryThe 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.
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 you need to ensure the session state has been saved before making the forwarded call.
+The following example configures a SaveSession GatewayFilter:
spring:
cloud:
@@ -1567,49 +1860,53 @@ using something like Spring
- 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.
+If you integrate Spring Security with Spring Session and want to ensure security details have been forwarded to the remote process, this is critical.
SecureHeaders GatewayFilter FactoryThe SecureHeaders GatewayFilter Factory adds a number of headers to the response at the recommendation from this blog post.
+The SecureHeaders GatewayFilter factory adds a number of headers to the response, per the recommendation made in this blog post.
The following headers (shown with their default values) are added:
X-Xss-Protection:1; mode=block
X-Xss-Protection:1 (mode=block)
Strict-Transport-Security:max-age=631138519
Strict-Transport-Security (max-age=631138519)
X-Frame-Options:DENY
X-Frame-Options (DENY)
X-Content-Type-Options:nosniff
X-Content-Type-Options (nosniff)
Referrer-Policy:no-referrer
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'
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-Download-Options (noopen)
X-Permitted-Cross-Domain-Policies:none
X-Permitted-Cross-Domain-Policies (none)
To change the default values set the appropriate property in the spring.cloud.gateway.filter.secure-headers namespace:
To change the default values, set the appropriate property in the spring.cloud.gateway.filter.secure-headers namespace.
+The following properties are available:
xss-protection-header
strict-transport-security
frame-options
content-type-options
referrer-policy
content-security-policy
download-options
permitted-cross-domain-policies
To disable the default values set the property spring.cloud.gateway.filter.secure-headers.disable with comma separated values.
| - - | --Need use lowercase and full name of secure headers. - | -
x-xss-protection
strict-transport-security
x-frame-options
spring.cloud.gateway.filter.secure-headers.disable=x-frame-options,strict-transport-security
To disable the default values set the spring.cloud.gateway.filter.secure-headers.disable property with comma-separated values.
+The following example shows how to do so:
spring.cloud.gateway.filter.secure-headers.disable=x-frame-options,strict-transport-security
+| + + | ++The lowercase full name of the secure header needs to be used to disable it.. + | +
SetPath GatewayFilter FactoryThe 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.
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.
+The following example configures a SetPath GatewayFilter:
spring:
cloud:
@@ -1701,22 +1981,27 @@ Need use lowercase and full name of secure headers.
- id: setpath_route
uri: https://example.org
predicates:
- - Path=/foo/{segment}
+ - Path=/red/{segment}
filters:
- SetPath=/{segment}
For a request path of /foo/bar, this will set the path to /bar before making the downstream request.
For a request path of /red/blue, this sets the path to /blue before making the downstream request.
SetRequestHeader GatewayFilter FactoryThe SetRequestHeader GatewayFilter Factory takes name and value parameters.
The SetRequestHeader GatewayFilter factory takes name and value parameters.
+The following listing configures a SetRequestHeader GatewayFilter:
spring:
cloud:
@@ -1725,17 +2010,24 @@ Need use lowercase and full name of secure headers.
- id: setrequestheader_route
uri: https://example.org
filters:
- - SetRequestHeader=X-Request-Foo, Bar
+ - SetRequestHeader=X-Request-Red, Blue
+This GatewayFilter replaces all headers with the given name, rather than adding. So if the downstream server responded with a X-Request-Foo:1234, this would be replaced with X-Request-Foo:Bar, which is what the downstream service would receive.
This GatewayFilter replaces (rather than adding) all headers with the given name.
+So, if the downstream server responded with a X-Request-Red:1234, this would be replaced with X-Request-Red:Blue, which is what the downstream service would receive.
SetRequestHeader is aware of URI variables used to match a path or host. URI variables may be used in the value and will be expanded at runtime.
+SetRequestHeader is aware of URI variables used to match a path or host.
+URI variables may be used in the value and are expanded at runtime.
+The following example configures an SetRequestHeader GatewayFilter that uses a variable:
spring:
cloud:
@@ -1750,13 +2042,18 @@ Need use lowercase and full name of secure headers.
The SetResponseHeader GatewayFilter Factory takes name and value parameters.
SetResponseHeader GatewayFilter FactoryThe SetResponseHeader GatewayFilter factory takes name and value parameters.
+The following listing configures a SetResponseHeader GatewayFilter:
spring:
cloud:
@@ -1765,17 +2062,24 @@ Need use lowercase and full name of secure headers.
- id: setresponseheader_route
uri: https://example.org
filters:
- - SetResponseHeader=X-Response-Foo, Bar
+ - SetResponseHeader=X-Response-Red, Blue
+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.
This GatewayFilter replaces (rather than adding) all headers with the given name.
+So, if the downstream server responded with a X-Response-Red:1234, this is replaced with X-Response-Red:Blue, which is what the gateway client would receive.
SetResponseHeader is aware of URI variables used to match a path or host. URI variables may be used in the value and will be expanded at runtime.
+SetResponseHeader is aware of URI variables used to match a path or host.
+URI variables may be used in the value and will be expanded at runtime.
+The following example configures an SetResponseHeader GatewayFilter that uses a variable:
spring:
cloud:
@@ -1790,13 +2094,20 @@ Need use lowercase and full name of secure headers.
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 FactoryThe SetStatus GatewayFilter factory takes a single parameter, status.
+It must be a valid Spring HttpStatus.
+It may be the integer value 404 or the string representation of the enumeration: NOT_FOUND.
+The following listing configures a SetStatus GatewayFilter:
spring:
cloud:
@@ -1812,14 +2123,19 @@ Need use lowercase and full name of secure headers.
- SetStatus=401
In either case, the HTTP status of the response will be set to 401.
+The SetStatus GatewayFilter can be configured to return the original HTTP status code from the proxied request in a header in the response. Header will be added to the response if configured using following property.
+In either case, the HTTP status of the response is set to 401.
You can configure the SetStatus GatewayFilter to return the original HTTP status code from the proxied request in a header in the response.
+The header is added to the response if configured with the following property:
spring:
cloud:
@@ -1829,13 +2145,19 @@ Need use lowercase and full name of secure headers.
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 FactoryThe StripPrefix GatewayFilter factory takes one parameter, parts.
+The parts parameter indicates the number of parts in the path to strip from the request before sending it downstream.
+The following listing configures a StripPrefix GatewayFilter:
spring:
cloud:
@@ -1849,63 +2171,71 @@ Need use lowercase and full name of secure headers.
- StripPrefix=2
When a request is made through the gateway to /name/bar/foo the request made to nameservice will look like nameservice/foo.
When a request is made through the gateway to /name/blue/red, the request made to nameservice looks like nameservice/red.
GatewayFilter FactoryThe Retry GatewayFilter Factory support following set of parameters:
+The Retry GatewayFilter factory supports the following parameters:
retries: the number of retries that should be attempted
retries: The number of retries that should be attempted.
statuses: the HTTP status codes that should be retried, represented using org.springframework.http.HttpStatus
statuses: The HTTP status codes that should be retried, represented by using org.springframework.http.HttpStatus.
methods: the HTTP methods that should be retried, represented using org.springframework.http.HttpMethod
methods: The HTTP methods that should be retried, represented by using org.springframework.http.HttpMethod.
series: the series of status codes to be retried, represented using org.springframework.http.HttpStatus.Series
series: The series of status codes to be retried, represented by using org.springframework.http.HttpStatus.Series.
exceptions: list of exceptions thrown that should be retried
exceptions: A list of thrown exceptions that should be retried.
backoff: configured exponential backoff for the retries. Retries are performed after a backoff interval of firstBackoff * (factor ^ n) where n is the iteration.
-If maxBackoff is configured, the maximum backoff applied will be limited to maxBackoff.
-If basedOnPreviousValue is true, backoff will be calculated using prevBackoff * factor.
backoff: The configured exponential backoff for the retries.
+Retries are performed after a backoff interval of firstBackoff * (factor ^ n), where n is the iteration.
+If maxBackoff is configured, the maximum backoff applied is limited to maxBackoff.
+If basedOnPreviousValue is true, the backoff is calculated byusing prevBackoff * factor.
The following defaults are configured for Retry filter if enabled:
The following defaults are configured for Retry filter, if enabled:
retries — 3 times
retries: Three times
series — 5XX series
series: 5XX series
methods — GET method
methods: GET method
exceptions — IOException and TimeoutException
exceptions: IOException and TimeoutException
backoff — disabled
backoff: disabled
The following listing configures a Retry GatewayFilter:
spring:
cloud:
@@ -1927,6 +2257,8 @@ If basedOnPreviousValue is true, backoff will be calculated using <
basedOnPreviousValue: false
| -The retry filter does not currently support retrying with a body (e.g. for POST or PUT requests with a body). +The retry filter does not currently support retrying with a body (for example, for POST or PUT requests with a body). |
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.
+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 (for example, through a Mono.error(ex) return value), which the retry filter can be configured to handle by retrying.
RequestSize GatewayFilter FactoryThe 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.
When the request size is greater than the permissible limit, the RequestSize GatewayFilter factory can restrict a request from reaching the downstream service.
+The filter takes a RequestSize parameter.
+It is the permissible size limit of the request defined in bytes.
+The following listing configures a RequestSize GatewayFilter:
spring:
cloud:
@@ -1974,11 +2313,19 @@ When using the retry filter with a forward: prefixed URL, the targe
maxSize: 5000000
The RequestSize GatewayFilter Factory set the response status as 413 Payload Too Large with a additional header errorMessage when 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 RequestSize GatewayFilter factory sets the response status as 413 Payload Too Large with an additional header errorMessage when the request is rejected due to size. The following example shows 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. +The default request size is set to five MB if not provided as a filter argument in the route definition. |
This filter is considered BETA and the API may change in the future
+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.
+You can use this filter to modify the request body before it is sent downstream by the gateway.
| -This filter can only be configured using the Java DSL +This filter can be configured only by using the Java DSL. |
The following listing shows how to modify a request body GatewayFilter:
@Bean
@@ -2045,13 +2406,24 @@ static class Hello {
This filter is considered BETA and the API may change in the future
+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.
+You can use this filter to modify the response body before it is sent back to the client.
| -This filter can only be configured using the Java DSL +This filter can be configured only by using the Java DSL. |
The following listing shows how to modify a response body GatewayFilter:
@Bean
@@ -2079,42 +2456,68 @@ public RouteLocator routes(RouteLocatorBuilder builder) {
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
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.
+The following listing defines a set of default filters:
spring:
cloud:
gateway:
default-filters:
- - AddResponseHeader=X-Response-Default-Foo, Default-Bar
+ - AddResponseHeader=X-Response-Default-Red, Default-Blue
- PrefixPath=/httpbin
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).
The GlobalFilter interface has the same signature as GatewayFilter.
+These are special filters that are conditionally applied to all routes.
| + + | ++This interface and its usage are subject to change in future milestone releases. + | +
GatewayFilter OrderingWhen 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.Ordered interface, which can be set by implementing the getOrder() method.
When a request matches a route, the filtering web handler adds 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.Ordered interface, which you can set by implementing the getOrder() method.
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.
+As Spring Cloud Gateway distinguishes between “pre” and “post” phases for filter logic execution (see How it Works), the filter with the highest precedence is the first in the “pre”-phase and the last in the “post”-phase.
The following listing configures a filter chain:
+@Bean
public GlobalFilter customFilter() {
@@ -2137,19 +2540,31 @@ public class CustomGlobalFilter implements GlobalFilter, Ordered {
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.
The ForwardRoutingFilter looks for a URI in the exchange attribute ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR.
+If the URL has a forward scheme (such as forward:///localendpoint), it uses the Spring DispatcherHandler to handle the request.
+The path part of the request URL is 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.
LoadBalancerClient FilterThe 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.
The LoadBalancerClientFilter looks for a URI in the exchange attribute named ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR.
+If the URL has a scheme of lb (such as lb://myservice), it uses the Spring Cloud LoadBalancerClient to resolve the name (myservice in this case) to an actual host and port and replaces 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 also looks in the ServerWebExchangeUtils.GATEWAY_SCHEME_PREFIX_ATTR attribute to see if it equals lb.
+If so, the same rules apply.
+The following listing configures a LoadBalancerClientFilter:
spring:
cloud:
@@ -2161,6 +2576,8 @@ public class CustomGlobalFilter implements GlobalFilter, Ordered {
- Path=/service/**
-By default when a service instance cannot be found in the LoadBalancer a 503 will be returned.
+By default, when a service instance cannot be found in the LoadBalancer, a 503 is 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.
+The isSecure value of the ServiceInstance returned from the LoadBalancer overrides
+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, the downstream request is 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 is stripped and the resulting scheme from the
+route URL overrides the ServiceInstance configuration.
|
ServiceInstance configuration.
LoadBalancerClientFilter uses a blocking Ribbon LoadBalancerClient under the hood.
+LoadBalancerClientFilter uses a blocking ribbon LoadBalancerClient under the hood.
We suggest you use ReactiveLoadBalancerClientFilter instead.
-You can switch to using it by setting the value of the spring.cloud.loadbalancer.ribbon.enabled to false.
+You can switch to it by setting the value of the spring.cloud.loadbalancer.ribbon.enabled to false.
ReactiveLoadBalancerClientFilterThe ReactiveLoadBalancerClientFilter 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 ReactorLoadBalancer 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.
The ReactiveLoadBalancerClientFilter looks for a URI in the exchange attribute named ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR.
+If the URL has a lb scheme (such as lb://myservice), it uses the Spring Cloud ReactorLoadBalancer to resolve the name (myservice in this example) to an actual host and port and replaces 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 also looks in the ServerWebExchangeUtils.GATEWAY_SCHEME_PREFIX_ATTR attribute to see if it equals lb.
+If so, the same rules apply.
+The following listing configures a ReactiveLoadBalancerClientFilter:
spring:
cloud:
@@ -2230,6 +2651,8 @@ The filter will also look in the ServerWebExchangeUtils.GATEWAY_SCHEME_PRE
- Path=/service/**
-By default when a service instance cannot be found by the ReactorLoadBalancer, a 503 will be returned.
-You can configure the Gateway to return a 404 by setting spring.cloud.gateway.loadbalancer.use404=true.
+By default, when a service instance cannot be found by the ReactorLoadBalancer, a 503 is returned.
+You can configure the gateway to return a 404 by setting spring.cloud.gateway.loadbalancer.use404=true.
|
404 by setting spri
-The isSecure value of the ServiceInstance returned from the ReactiveLoadBalancerClientFilter 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.
+The isSecure value of the ServiceInstance returned from the ReactiveLoadBalancerClientFilter overrides
+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, the downstream request is 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 is stripped and the resulting scheme from the route URL overrides the ServiceInstance configuration.
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)
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 also an experimental WebClientHttpRoutingFilter that performs the same function but does not require Netty.)
The NettyWriteResponseFilter runs if there is a Netty HttpClientResponse in the ServerWebExchangeUtils.CLIENT_RESPONSE_ATTR exchange 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)
The NettyWriteResponseFilter runs if there is a Netty HttpClientResponse in the ServerWebExchangeUtils.CLIENT_RESPONSE_ATTR exchange attribute.
+It runs after all other filters have completed and writes the proxy response back to the gateway client response.
+(There is also an experimental WebClientWriteResponseFilter that performs the same function but does not require Netty.)
RouteToRequestUrl FilterThe 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 there is a Route object in the ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR exchange attribute, the RouteToRequestUrlFilter runs.
+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:ws://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.
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.
If the URL located in the ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR exchange attribute has a ws or wss scheme, the websocket routing rilter runs. It uses the Spring WebSocket infrastructure to forward the websocket request downstream.
Websockets may be load-balanced by prefixing the URI with lb, such as lb:ws://serviceid.
You can load-balance websockets by prefixing the URI with lb, such as lb:ws://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. +If you use SockJS as a fallback over normal HTTP, you should configure a normal HTTP route as well as the websocket Route. |
The following listing configures a websocket routing filter:
+spring:
cloud:
@@ -2322,30 +2756,32 @@ If you are using SockJS as a fallback ov
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:
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:
routeId: The route id
routeId: The route ID.
routeUri: The URI that the API will be routed to
routeUri: The URI to which the API is routed.
outcome: Outcome as classified by HttpStatus.Series
outcome: The outcome, as classified by HttpStatus.Series.
status: Http Status of the request returned to the client
status: The HTTP status of the request returned to the client.
httpStatusCode: Http Status of the request returned to the client
httpStatusCode: The HTTP Status of the request returned to the client.
httpMethod: The Http method used for the request
httpMethod: The HTTP method used for the request.
micrometer-registry-prometheus as a project dependency.
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
+
After the gateway has routed a ServerWebExchange, it marks 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.
ServerWebExchangeUtils.isAlreadyRouted takes a ServerWebExchange object and checks if it has been "routed"
ServerWebExchangeUtils.isAlreadyRouted takes a ServerWebExchange object and checks if it has been “routed”.
ServerWebExchangeUtils.setAlreadyRouted takes a ServerWebExchange object and marks it as "routed"
ServerWebExchangeUtils.setAlreadyRouted takes a ServerWebExchange object and marks it as “routed”.
The Gateway can listen for requests on https by following the usual Spring server configuration. Example:
+The gateway can listen for requests on HTTPS by following the usual Spring server configuration. +The following example shows how to do so:
server:
ssl:
@@ -2404,11 +2843,16 @@ or check if an exchange has already been routed.
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:
You can route gateway routes to both HTTP and HTTPS backends. +If you are routing to an HTTPS backend, you can configure the gateway to trust all downstream certificates with the following configuration:
+spring:
cloud:
@@ -2418,11 +2862,16 @@ or check if an exchange has already been routed.
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:
Using an insecure trust manager is not suitable for production. +For a production deployment, you can configure the gateway with a set of known certificates that it can trust with the following configuration:
+spring:
cloud:
@@ -2434,16 +2883,23 @@ or check if an exchange has already been routed.
- 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).
+If the Spring Cloud Gateway is not provisioned with trusted certificates, the default trust store is used (which you can override by setting the javax.net.ssl.trustStore system property).
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):
+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. +You can configure these timeouts can be configured (defaults shown) as follows:
spring:
cloud:
@@ -2458,28 +2914,38 @@ or check if an exchange has already been routed.
Configuration for Spring Cloud Gateway is driven by a collection of RouteDefinitionLocators.
Configuration for Spring Cloud Gateway is driven by a collection of RouteDefinitionLocator instances.
+The following listing shows the definition of the RouteDefinitionLocator interface:
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:
+By default, a PropertiesRouteDefinitionLocator loads properties by using Spring Boot’s @ConfigurationProperties mechanism.
The earlier configuration examples all use a shortcut notation that uses positional arguments rather than named ones. +The following two examples are equivalent:
+spring:
cloud:
@@ -2497,19 +2963,23 @@ or check if an exchange has already been routed.
- 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 RouteDefinitionLocator implementations based off of Spring Data Repositories such as: Redis, MongoDB and Cassandra.
For some usages of the gateway, properties are adequate, but some production use cases benefit from loading configuration from an external source, such as a database. Future milestone versions will have RouteDefinitionLocator implementations based off of Spring Data Repositories, such as Redis, MongoDB, and Cassandra.
Additional parameters can be configured for each route using metadata:
+You can configure additional parameters for each route by using metadata, as follows:
spring:
cloud:
@@ -2524,9 +2994,13 @@ or check if an exchange has already been routed.
iAmNumber: 1
All metadata properties could be acquired from exchange:
You could acquire all metadata properties from an exchange, as follows:
+Route route = exchange.getAttribute(GATEWAY_ROUTE_ATTR);
@@ -2538,6 +3012,8 @@ route.getMetadata(someKey);
To allow for simple configuration in Java, there is a fluent API defined in the RouteLocatorBuilder bean.
To allow for simple configuration in Java, the RouteLocatorBuilder bean includes a fluent API.
+The following listing shows how it works:
// static imports from GatewayFilters and RoutePredicates
@Bean
@@ -2641,40 +3120,44 @@ public RouteLocator customRouteLocator(RouteLocatorBuilder builder, ThrottleGate
}
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 Predicate class.
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 Predicate class.
DiscoveryClient Route Definition LocatorThe Gateway can be configured to create routes based on services registered with a DiscoveryClient compatible service registry.
You can configure the gateway to create routes based on services registered with a DiscoveryClient compatible service registry.
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).
To enable this, set spring.cloud.gateway.discovery.locator.enabled=true and make sure a DiscoveryClient implementation (such as Netflix Eureka, Consul, or Zookeeper) is on the classpath and enabled.
DiscoveryClient RoutesBy default the Gateway defines a single predicate and filter for routes created via a DiscoveryClient.
By default, the fateway defines a single predicate and filter for routes created with 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.
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.
The default filter is a rewrite path filter with the regex /serviceId/(?<remaining>.*) and the replacement /${remaining}.
+This 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.
If you want to customize the predicates or filters used by the DiscoveryClient routes, set 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 shown earlier, if you want to retain that functionality.
+The following example shows what this looks like:
spring.cloud.gateway.discovery.locator.predicates[0].name: Path
spring.cloud.gateway.discovery.locator.predicates[0].args[pattern]: "'/'+serviceId+'/**'"
@@ -2691,17 +3174,33 @@ spring.cloud.gateway.discovery.locator.filters[1].args[replacement]: "'/${remain
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).
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:
+You can configure the logging system to have a separate access log file. The following example creates a Logback configuration:
<appender name="accessLog" class="ch.qos.logback.core.FileAppender">
<file>access_log.log</file>
@@ -2720,14 +3219,19 @@ spring.cloud.gateway.discovery.locator.filters[1].args[replacement]: "'/${remain
The gateway can be configured to control CORS behavior. The "global" CORS configuration is a map of URL patterns to Spring Framework CorsConfiguration.
You can configure the gateway to control CORS behavior. The “global” CORS configuration is a map of URL patterns to Spring Framework CorsConfiguration.
+The following example configures CORS:
spring:
cloud:
@@ -2740,11 +3244,14 @@ spring.cloud.gateway.discovery.locator.filters[1].args[replacement]: "'/${remain
- GET
In the example above, CORS requests will be allowed from requests that originate from docs.spring.io for all GET requested paths.
+To provide the same CORS configuration to requests that are not handled by some gateway route predicate, set the property spring.cloud.gateway.globalcors.add-to-simple-url-handler-mapping equal to true. This is useful when trying to support CORS preflight requests and your route predicate doesn’t evalute to true because the http method is options.
In the preceding example, CORS requests are allowed from requests that originate from docs.spring.io for all GET requested paths.
To provide the same CORS configuration to requests that are not handled by some gateway route predicate, set the spring.cloud.gateway.globalcors.add-to-simple-url-handler-mapping property to true.
+This is useful when you try to support CORS preflight requests and your route predicate does not evalute to true because the HTTP method is options.
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.
The /gateway actuator endpoint lets you monitor and interact with a Spring Cloud Gateway application.
+To be remotely accessible, the endpoint has to be enabled and exposed over HTTP or JMX in the application properties.
+The following listing shows how to do so:
management.endpoint.gateway.enabled=true # default value
management.endpoints.web.exposure.include=gateway
A new, more verbose format has been added to Gateway. This adds more detail to each route allowing to view the predicates and filters associated to each route along with any configuration that is available.
-/actuator/gateway/routes
A new, more verbose format has been added to Spring Cloud Gateway.
+It adds more detail to each route, letting you view the predicates and filters associated with each route along with any configuration that is available.
+The following example configures /actuator/gateway/routes:
[
@@ -2786,26 +3300,47 @@ management.endpoints.web.exposure.include=gateway
]
This feature is enabled by default. To disable it, set the following property:
spring.cloud.gateway.actuator.verbose.enabled=false
This will default to true in a future release.
+This will default to true in a future release.
This section details how to retrieve route filters, including:
+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:
{
@@ -2820,15 +3355,21 @@ management.endpoints.web.exposure.include=gateway
}
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.
The response contains the details of the global filters that are in place.
+For each global filter, there is a string representation of the filter object (for example, org.springframework.cloud.gateway.filter.LoadBalancerClientFilter@77856cc5) and the corresponding order in the filter chain.}
To retrieve the GatewayFilter factories applied to routes, make a GET request to /actuator/gateway/routefilters. The resulting response is similar to the following:
To retrieve the GatewayFilter factories applied to routes, make a GET request to /actuator/gateway/routefilters.
+The resulting response is similar to the following:
{
@@ -2838,22 +3379,30 @@ management.endpoints.web.exposure.include=gateway
}
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.
The response contains the details of the GatewayFilter factories applied to any particular route.
+For each factory there is a string representation of the corresponding object (for example, [SecureHeadersGatewayFilterFactory@fceab5d configClass = Object]).
+Note that the null value is due to an incomplete implementation of the endpoint controller, because it tries to set the order of the object in the filter chain, which does not apply to a GatewayFilter factory object.
To clear the routes cache, make a POST request to /actuator/gateway/refresh. The request returns a 200 without response body.
To clear the routes cache, make a POST request to /actuator/gateway/refresh.
+The request returns a 200 without a response body.
To retrieve the routes defined in the gateway, make a GET request to /actuator/gateway/routes. The resulting response is similar to the following:
To retrieve the routes defined in the gateway, make a GET request to /actuator/gateway/routes.
+The resulting response is similar to the following:
[{
@@ -2876,8 +3425,11 @@ management.endpoints.web.exposure.include=gateway
}]
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 response contains the details of all the routes defined in the gateway. +The following table describes the structure of each element (each is a route) of the response:
|
String |
-The route id. |
+The route ID. |
|
@@ -2906,7 +3458,7 @@ management.endpoints.web.exposure.include=gateway
|||
|
Array |
-The GatewayFilter factories applied to the route. |
+The |
|
@@ -2917,10 +3469,13 @@ management.endpoints.web.exposure.include=gateway
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:
To retrieve information about a single route, make a GET request to /actuator/gateway/routes/{id} (for example, /actuator/gateway/routes/first_route).
+The resulting response is similar to the following:
{
@@ -2935,8 +3490,10 @@ management.endpoints.web.exposure.include=gateway
}]
The following table describes the structure of the response.
+The following table describes the structure of the response:
|
String |
-The route id. |
+The route ID. |
|
@@ -2981,18 +3538,18 @@ management.endpoints.web.exposure.include=gateway
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 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 Retrieving Information about a Particular Route).
To delete a route, make a DELETE request to /gateway/routes/{id_route_to_delete}.
The table below summarises the Spring Cloud Gateway actuator endpoints. Note that each endpoint has /actuator/gateway as the base-path.
The folloiwng table below summarizes the Spring Cloud Gateway actuator endpoints (note that each endpoint has /actuator/gateway as the base-path):
|
GET |
-Displays the list of GatewayFilter factories applied to a particular route. |
+Displays the list of |
|
@@ -3036,12 +3593,12 @@ management.endpoints.web.exposure.include=gateway
|||
|
POST |
-Add a new route to the gateway. |
+Adds a new route to the gateway. |
|
DELETE |
-Remove an existing route from the gateway. |
+Removes an existing route from the gateway. |
This section covers common problems that may arise when you use Spring Cloud Gateway.
+Below are some useful loggers that contain valuable trouble shooting infomration at the DEBUG and TRACE levels.
The following loggers may contain valuable troubleshooting information at the DEBUG and TRACE levels:
The Reactor Netty HttpClient and HttpServer can have wiretap enabled. When combined
-with setting the reactor.netty log level to DEBUG or TRACE will enable logging of
-information such as headers and bodies sent and received across the wire. To enable this,
-set spring.cloud.gateway.httpserver.wiretap=true and/or
-spring.cloud.gateway.httpclient.wiretap=true for the HttpServer and HttpClient
-respectively.
The Reactor Netty HttpClient and HttpServer can have wiretap enabled.
+When combined with setting the reactor.netty log level to DEBUG or TRACE, it enables the logging of information, such as headers and bodies sent and received across the wire.
+To enable wiretap, set spring.cloud.gateway.httpserver.wiretap=true or spring.cloud.gateway.httpclient.wiretap=true for the HttpServer and HttpClient, respectively.
In order to write a GatewayFilter you will need to implement GatewayFilterFactory. There is an abstract class called AbstractGatewayFilterFactory which you can extend.
To write a GatewayFilter, you must implement GatewayFilterFactory.
+You can extend an abstract class called AbstractGatewayFilterFactory.
+The following examples show how to do so:
public class PreGatewayFilterFactory extends AbstractGatewayFilterFactory<PreGatewayFilterFactory.Config> {
@@ -3165,14 +3726,19 @@ respectively.
In order to write a custom global filter, you will need to implement GlobalFilter interface. This will apply the filter to all requests.
To write a custom global filter, you must implement GlobalFilter interface.
+This applies the filter to all requests.
Example of how to set up a Global Pre and Post filter, respectively
+The following examples show how to set up global pre and post filters, respectively:
@Bean
@@ -3203,6 +3769,8 @@ public GlobalFilter customGlobalPostFilter() {
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).
Spring Cloud Gateway provides a utility object called ProxyExchange.
+You can use it inside a regular Spring web handler as a method parameter.
+It supports basic downstream HTTP exchanges through methods that mirror the HTTP verbs.
+With MVC, it also supports forwarding to a local handler through the forward() method.
+To use the ProxyExchange, 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):
+The following MVC example proxies a request to /test downstream to a remote server:
@RestController
@@ -3237,9 +3811,13 @@ public class GatewaySampleApplication {
}
The same thing with Webflux:
The following example does the same thing with Webflux:
+@RestController
@@ -3257,9 +3835,14 @@ public class GatewaySampleApplication {
}
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:
Convenience methods on the ProxyExchange 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/**")
@@ -3269,17 +3852,22 @@ public ResponseEntity<?> proxyPath(ProxyExchange<byte[]> proxy) thro
}
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.
All the features of Spring MVC and Webflux are available to gateway handler methods.
+As a result, 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.
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.
You can add headers to the downstream response by using the header() methods on ProxyExchange.
First class support is provided for "sensitive" headers ("cookie" and "authorization" by default) which are not passed downstream, and for "proxy" headers (x-forwarded-*).
You can also manipulate response headers (and anything else you like in the response) by adding a mapper to the get() method (and other methods).
+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 (by default, cookie and authorization), which are not passed downstream, and for “proxy” (x-forwarded-*) headers.
To see the list of all Spring Cloud Gateway related configuration properties please check the Appendix page.
+To see the list of all Spring Cloud Gateway related configuration properties, see the appendix.
GatewayFilter Factories
AddRequestHeader GatewayFilter FactoryAddRequestParameter GatewayFilter FactoryAddResponseHeader GatewayFilter FactoryDedupeResponseHeader GatewayFilter FactoryGatewayFilter FactoryFallbackHeaders GatewayFilter FactoryMapRequestHeader GatewayFilter FactoryPrefixPath GatewayFilter FactoryPreserveHostHeader GatewayFilter FactoryRequestRateLimiter GatewayFilter Factory
RedirectTo GatewayFilter FactoryRemoveHopByHopHeadersFilter GatewayFilter FactoryRemoveRequestHeader GatewayFilter FactoryRemoveResponseHeader GatewayFilter FactoryRemoveRequestParameter GatewayFilter FactoryRewritePath GatewayFilter FactoryRewriteLocationResponseHeader GatewayFilter FactoryRewriteResponseHeader GatewayFilter FactorySaveSession GatewayFilter FactorySecureHeaders GatewayFilter FactorySetPath GatewayFilter FactorySetRequestHeader GatewayFilter FactorySetResponseHeader GatewayFilter FactorySetStatus GatewayFilter FactoryStripPrefix GatewayFilter FactoryGatewayFilter FactoryRequestSize GatewayFilter FactoryGatewayFilter FactoryGatewayFilter FactoryGatewayFilter OrderingLoadBalancerClient FilterReactiveLoadBalancerClientFilterRouteToRequestUrl FilterTo 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.
To include Spring Cloud Gateway in your project, use the starter with a group ID of org.springframework.cloud and an artifact ID of 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.
If you include the starter, but, for some reason, you do not want the gateway to be enabled, set spring.cloud.gateway.enabled=false.
If you include the starter, but you do not want the gateway to be enabled, set spring.cloud.gateway.enabled=false.
| -Spring Cloud Gateway is built upon Spring Boot 2.x, -Spring 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 is built on Spring Boot 2.x, Spring WebFlux, and Project Reactor. +As a consequence, many of the familiar synchronous libraries (Spring Data and Spring Security, for example) and patterns you know may not apply when you use 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. |
Route: Route the basic building block of the gateway. It is defined by an ID, a destination URI, a collection of predicates and a collection of filters. A route is matched if aggregate predicate is true.
+Route: The basic building block of the gateway. +It is defined by an ID, a destination URI, a collection of predicates, and a collection of filters. A route is matched if the aggregate predicate is true.
Predicate: This is a Java 8 Function Predicate. The input type is a Spring Framework ServerWebExchange. This allows developers to match on anything from the HTTP request, such as headers or parameters.
Predicate: This is a Java 8 Function Predicate. The input type is a Spring Framework ServerWebExchange.
+This lets you match on anything from the HTTP request, such as headers or parameters.
Filter: These are instances Spring Framework GatewayFilter constructed in with a specific factory. Here, requests and responses can be modified before or after sending the downstream request.
Filter: These are instances of Spring Framework GatewayFilter that have been constructed with a specific factory.
+Here, you can modify requests and responses before or after sending the downstream request.
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.
+The following diagram provides a high-level overview of how Spring Cloud Gateway works:
+
+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 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 can run logic both before and after the proxy request is sent. +All “pre” filter logic is executed. Then the proxy request is made. After the proxy request is made, the “post” filter logic is run.
| -URIs defined in routes without a port will get a default port set to 80 and 443 for HTTP and HTTPS URIs respectively. +URIs defined in routes without a port get default port values of 80 and 443 for the HTTP and HTTPS URIs, respectively. |
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 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.
+You can combine multiple route predicate factories with logical and statements.
The After Route Predicate Factory takes one parameter, a datetime. This predicate matches requests that happen after the current datetime.
+The after route predicate factory takes one parameter, a datetime. +This predicate matches requests that happen after the specified datetime. +The following example configures an after route predicate:
spring:
cloud:
@@ -343,17 +360,23 @@ URIs defined in routes without a port will get a default port set to 80 and 443
- 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).
+This route matches any request made after Jan 20, 2017 17:42 Mountain Time (Denver).
The Before Route Predicate Factory takes one parameter, a datetime. This predicate matches requests that happen before the current datetime.
+The before route predicate factory takes one parameter, a datetime.
+This predicate matches requests that happen before the specified datetime.
+The following example configures a before route predicate:
spring:
cloud:
@@ -365,17 +388,24 @@ URIs defined in routes without a port will get a default port set to 80 and 443
- 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).
+This route matches any request made before Jan 20, 2017 17:42 Mountain Time (Denver).
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.
+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.
+The following example configures a between route predicate:
spring:
cloud:
@@ -387,17 +417,24 @@ URIs defined in routes without a port will get a default port set to 80 and 443
- 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.
+This route matches any request made 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.
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.
+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 whose values match the regular expression. +The following example configures a cookie route predicate factory:
spring:
cloud:
@@ -409,17 +446,23 @@ URIs defined in routes without a port will get a default port set to 80 and 443
- Cookie=chocolate, ch.p
This route matches the request has a cookie named chocolate who’s value matches the ch.p regular expression.
This route matches requests that have a cookie named chocolate whose value matches the ch.p regular expression.
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.
+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 whose value matches the regular expression. +The following example configures a header route predicate:
spring:
cloud:
@@ -431,17 +474,24 @@ URIs defined in routes without a port will get a default port set to 80 and 443
- 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).
This route matches if the request has a header named X-Request-Id whose value matches the \d+ regular expression (that is, it has a value of one or more digits).
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.
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.
+The following example configures a host route predicate:
spring:
cloud:
@@ -453,23 +503,29 @@ URIs defined in routes without a port will get a default port set to 80 and 443
- 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.
URI template variables (such as {sub}.myhost.org) are supported as well.
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
This route matches if the request has a Host header with a value of www.somehost.org or beta.somehost.org or www.anotherhost.org.
This predicate extracts the URI template variables (such as sub, defined in the preceding example) 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
The Method Route Predicate Factory takes one or more parameters: the HTTP methods to match.
+The Method Route Predicate Factory takes one or more parameters: the HTTP methods to match. +The following example configures a method route predicate:
spring:
cloud:
@@ -481,17 +537,22 @@ URIs defined in routes without a port will get a default port set to 80 and 443
- Method=GET,POST
This route would match if the request method was a GET or a POST.
This route matches if the request method was a GET or a POST.
The Path Route Predicate Factory takes two parameters: a list of Spring PathMatcher patterns and an optional flag to matchOptionalTrailingSeparator.
The Path Route Predicate Factory takes two parameters: a list of Spring PathMatcher patterns and an optional flag called matchOptionalTrailingSeparator.
+The following example configures a path route predicate:
spring:
cloud:
@@ -500,18 +561,24 @@ URIs defined in routes without a port will get a default port set to 80 and 443
- id: host_route
uri: https://example.org
predicates:
- - Path=/foo/{segment},/bar/{segment}
+ - Path=/red/{segment},/blue/{segment}
+This route would match if the request path was, for example: /foo/1 or /foo/bar or /bar/baz.
This route matches if the request path was, for example: /red/1 or /red/blue or /blue/green.
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
This predicate extracts the URI template variables (such as segment, defined in the preceding example) 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.
+A utility method (called get) is available to make access to these variables easier.
+The following example shows how to use the get method:
Map<String, String> uriVariables = ServerWebExchangeUtils.getPathPredicateVariables(exchange);
@@ -520,10 +587,33 @@ String segment = uriVariables.get("segment");
The Query Route Predicate Factory takes two parameters: a required param and an optional regexp.
The query route predicate factory takes two parameters: a required param and an optional regexp.
+The following example configures a query route predicate:
spring:
+ cloud:
+ gateway:
+ routes:
+ - id: query_route
+ uri: https://example.org
+ predicates:
+ - Query=green
+The preceding route matches if the request contained a green query parameter.
This route would match if the request contained a baz query parameter.
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 baz would match.
The preceding route matches if the request contained a red query parameter whose value matched the gree. regexp, so green and greet would match.
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).
The RemoteAddr route predicate factory takes a list (min size 1) of CIDR-notation (IPv4 or IPv6) strings, such as 192.168.0.1/16 (where 192.168.0.1 is an IP address and 16 is a subnet mask).
+The following example configures a RemoteAddr route predicate:
spring:
cloud:
@@ -576,17 +653,22 @@ String segment = uriVariables.get("segment");
- RemoteAddr=192.168.1.1/24
This route would match if the remote address of the request was, for example, 192.168.1.10.
This route matches if the remote address of the request was, for example, 192.168.1.10.
The Weight Route Predicate Factory takes two argument group and weight. The weights are calculated per group.
+The weight route predicate factory takes two arguments: group and weight. The weights are calculated per group. +The following example configures a weight route predicate:
spring:
cloud:
@@ -602,41 +684,51 @@ String segment = uriVariables.get("segment");
- Weight=group1, 2
This route would forward ~80% of traffic to weighthigh.org and ~20% of traffic to weighlow.org
By default the RemoteAddr Route Predicate Factory uses the remote address from the incoming request. +
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.
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.
XForwardedRemoteAddressResolver.
XForwardedRemoteAddressResolver has two static constructor methods which take different approaches to security:
XForwardedRemoteAddressResolver has two static constructor methods, which take different approaches to security:
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.
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.
+
XForwardedRemoteAddressResolver::trustAll returns a RemoteAddressResolver that 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.
XForwardedRemoteAddressResolver::maxTrustedIndex takes an index that correlates to the number of trusted infrastructure running in front of Spring Cloud Gateway.
+If Spring Cloud Gateway is, for example only accessible through 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:
+Consider 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.
The following maxTrustedIndex values yield the following remote addresses:
Using Java config:
-GatewayConfig.java
+The following example shows how to achieve the same configuration with Java:
RemoteAddressResolver resolver = XForwardedRemoteAddressResolver
@@ -689,7 +781,7 @@ If two hops of trusted infrastructure are required before Spring Cloud Gateway i
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")
+ r -> r.remoteAddr(resolver, "10.10.1.1", "10.10.1.1/24")
.uri("https://downstream2")
)
GatewayFilter FactoriesRoute 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.
+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.
NOTE For more detailed examples on how to use any of the following filters, take a look at the unit tests.
+| + + | ++For more detailed examples of how to use any of the following filters, take a look at the unit tests. + | +
AddRequestHeader GatewayFilter FactoryThe AddRequestHeader GatewayFilter Factory takes a name and value parameter.
+The AddRequestHeader GatewayFilter factory takes a name and value parameter.
+The following example configures an AddRequestHeader GatewayFilter:
spring:
cloud:
@@ -722,17 +830,23 @@ If two hops of trusted infrastructure are required before Spring Cloud Gateway i
- id: add_request_header_route
uri: https://example.org
filters:
- - AddRequestHeader=X-Request-Foo, Bar
+ - AddRequestHeader=X-Request-red, blue
+This will add X-Request-Foo:Bar header to the downstream request’s headers for all matching requests.
This listing adds X-Request-red:blue header to the downstream request’s headers for all matching requests.
AddRequestHeader is aware of URI variables used to match a path or host. URI variables may be used in the value and will be expanded at runtime.
+AddRequestHeader is aware of the URI variables used to match a path or host.
+URI variables may be used in the value and are expanded at runtime.
+The following example configures an AddRequestHeader GatewayFilter that uses a variable:
spring:
cloud:
@@ -741,19 +855,24 @@ If two hops of trusted infrastructure are required before Spring Cloud Gateway i
- id: add_request_header_route
uri: https://example.org
predicates:
- - Path=/foo/{segment}
+ - Path=/red/{segment}
filters:
- - AddRequestHeader=X-Request-Foo, Bar-{segment}
+ - AddRequestHeader=X-Request-Red, Blue-{segment}
+AddRequestParameter GatewayFilter FactoryThe AddRequestParameter GatewayFilter Factory takes a name and value parameter.
+The AddRequestParameter GatewayFilter Factory takes a name and value parameter.
+The following example configures an AddRequestParameter GatewayFilter:
spring:
cloud:
@@ -762,17 +881,23 @@ If two hops of trusted infrastructure are required before Spring Cloud Gateway i
- id: add_request_parameter_route
uri: https://example.org
filters:
- - AddRequestParameter=foo, bar
+ - AddRequestParameter=red, blue
+This will add foo=bar to the downstream request’s query string for all matching requests.
This will add red=blue to the downstream request’s query string for all matching requests.
AddRequestParameter is aware of URI variables used to match a path or host. URI variables may be used in the value and will be expanded at runtime.
+AddRequestParameter is aware of the URI variables used to match a path or host.
+URI variables may be used in the value and are expanded at runtime.
+The following example configures an AddRequestParameter GatewayFilter that uses a variable:
spring:
cloud:
@@ -787,13 +912,18 @@ If two hops of trusted infrastructure are required before Spring Cloud Gateway i
The AddResponseHeader GatewayFilter Factory takes a name and value parameter.
AddResponseHeader GatewayFilter FactoryThe AddResponseHeader GatewayFilter Factory takes a name and value parameter.
+The following example configures an AddResponseHeader GatewayFilter:
spring:
cloud:
@@ -802,17 +932,23 @@ If two hops of trusted infrastructure are required before Spring Cloud Gateway i
- id: add_response_header_route
uri: https://example.org
filters:
- - AddResponseHeader=X-Response-Foo, Bar
+ - AddResponseHeader=X-Response-Red, Blue
+This will add X-Response-Foo:Bar header to the downstream response’s headers for all matching requests.
This adds X-Response-Foo:Bar header to the downstream response’s headers for all matching requests.
AddResponseHeader is aware of URI variables used to match a path or host. URI variables may be used in the value and will be expanded at runtime.
+AddResponseHeader is aware of URI variables used to match a path or host.
+URI variables may be used in the value and are expanded at runtime.
+The following example configures an AddResponseHeader GatewayFilter that uses a variable:
spring:
cloud:
@@ -827,13 +963,18 @@ If two hops of trusted infrastructure are required before Spring Cloud Gateway i
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 FactoryThe DedupeResponseHeader GatewayFilter factory takes a name parameter and an optional strategy parameter. name can contain a space-separated list of header names.
+The following example configures a DedupeResponseHeader GatewayFilter:
spring:
cloud:
@@ -845,15 +986,18 @@ If two hops of trusted infrastructure are required before Spring Cloud Gateway i
- 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.
The DedupeResponseHeader filter also accepts an optional strategy parameter. The accepted values are RETAIN_FIRST (default), RETAIN_LAST, and RETAIN_UNIQUE.
This removes 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 logic add them.
The DedupeResponseHeader filter also accepts an optional strategy parameter.
+The accepted values are RETAIN_FIRST (default), RETAIN_LAST, and RETAIN_UNIQUE.
GatewayFilter Factory| -Netflix has put Hystrix in maintenance mode. It is suggested you use the Spring Cloud CircuitBreaker -Gateway Filter with Resilience4J as support for Hystrix will be removed in a future release. +Netflix has put Hystrix in maintenance mode. We suggest you use the Spring Cloud CircuitBreaker +Gateway Filter with Resilience4J, as support for Hystrix will be removed in a future release. |
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.
+The HystrixGatewayFilter lets you introduce circuit breakers to your gateway routes, protecting your services from cascading failures and letting you 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.
To enable Hystrix GatewayFilter instances 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.
The Hystrix GatewayFilter factory requires a single name parameter, which is the name of the HystrixCommand.
+The following example configures a Hystrix GatewayFilter:
spring:
cloud:
@@ -890,14 +1037,19 @@ The Hystrix GatewayFilter allows you to introduce circuit breakers to your gatew
- 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.
This wraps the remaining filters in a HystrixCommand with a command name of 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 is forwarded to the controller matched by the URI.
+The following example configures such a fallback:
spring:
cloud:
@@ -915,15 +1067,19 @@ The Hystrix GatewayFilter allows you to introduce circuit breakers to your gatew
- 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.
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 (defined the lb prefix on the destination URI).
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:
spring:
cloud:
@@ -944,46 +1100,52 @@ However, it is also possible to reroute the request to a controller or handler i
- 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 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.
In this example, there is no fallback endpoint or handler in the gateway application.
+However, there is one in another application, registered under localhost:9994.
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.
+In case of the request being forwarded to the fallback, the Hystrix Gateway filter also provides the Throwable that has caused it.
+It is added to the ServerWebExchange as the ServerWebExchangeUtils.HYSTRIX_EXECUTION_EXCEPTION_ATTR attribute, which you can use when handling the fallback within the gateway application.
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.
+For the external controller/handler scenario, you can add headers with exception details. +You can find more information on doing so in the FallbackHeaders GatewayFilter Factory section.
To set a 5 second timeout for the example route above, the following configuration would be used:
+You can configured Hystrix settings (such as timeouts) with global defaults or on a route-by-route basis by using application properties, as explained on the Hystrix wiki.
To set a five-second timeout for the example route shown earlier, you could use the following configuration:
+hystrix.command.fallbackcmd.execution.isolation.thread.timeoutInMilliseconds: 5000
The Spring Cloud CircuitBreaker filter factory leverages the Spring Cloud CircuitBreaker APIs to wrap Gateway routes in -a circuit breaker. Spring Cloud CircuitBreaker supports two libraries which can be used with Spring Cloud Gateway, Hystrix -and Resilience4J. Since Netflix has places Hystrix in maintenance only mode we suggest you use Resilience4J.
+The Spring Cloud CircuitBreaker GatewayFilter factory uses the Spring Cloud CircuitBreaker APIs to wrap Gateway routes in +a circuit breaker. Spring Cloud CircuitBreaker supports two libraries that can be used with Spring Cloud Gateway, Hystrix +and Resilience4J. Since Netflix has placed Hystrix in maintenance-only mode, we suggest that you use Resilience4J.
To enable the Spring Cloud CircuitBreaker filter you will need to either place spring-cloud-starter-circuitbreaker-reactor-resilience4j or
-spring-cloud-starter-netflix-hystrix on the classpath.
To enable the Spring Cloud CircuitBreaker filter, you need to place either spring-cloud-starter-circuitbreaker-reactor-resilience4j or spring-cloud-starter-netflix-hystrix on the classpath.
+The following example configures a Spring Cloud CircuitBreaker GatewayFilter:
spring:
cloud:
@@ -995,6 +1157,8 @@ and Resilience4J. Since Netflix has places Hystrix in maintenance only mode we
- CircuitBreaker=myCircuitBreaker
To configure the circuit breaker, see the configuration for the underlying circuit breaker implementation you are using.
The Spring Cloud CircuitBreaker 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.
The Spring Cloud CircuitBreaker filter can also accept an optional fallbackUri parameter.
+Currently, only forward: schemed URIs are supported.
+If the fallback is called, the request is forwarded to the controller matched by the URI.
+The following example configures such a fallback:
spring:
cloud:
@@ -1030,8 +1199,15 @@ and Resilience4J. Since Netflix has places Hystrix in maintenance only mode we
- RewritePath=/consumingServiceEndpoint, /backingServiceEndpoint
The following listing does the same thing in Java:
+@Bean
public RouteLocator routes(RouteLocatorBuilder builder) {
@@ -1043,15 +1219,20 @@ public RouteLocator routes(RouteLocatorBuilder builder) {
}
This will forward to the /inCaseofFailureUseThis URI when the circuit breaker fallback is called. Note that this example also demonstrates (optional) Spring Cloud Netflix Ribbon load-balancing via the lb prefix on the destination URI.
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:
This example forwards to the /inCaseofFailureUseThis URI when the circuit breaker fallback is called.
+Note that this example also demonstrates the (optional) Spring Cloud Netflix Ribbon load-balancing (defined by the lb prefix on the destination URI).
The primary scenario is to use the fallbackUri to define an internal controller or handler within the gateway application.
+However, you can also reroute the request to a controller or handler in an external application, as follows:
spring:
cloud:
@@ -1072,29 +1253,30 @@ However, it is also possible to reroute the request to a controller or handler i
- 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 localhost:9994.
In case of the request being forwarded to fallback, the Spring Cloud CircuitBreaker Gateway filter also provides the Throwable that has
-caused it. It’s added to the ServerWebExchange as the
-ServerWebExchangeUtils.CIRCUITBREAKER_EXECUTION_EXCEPTION_ATTR attribute that can be used when
-handling the fallback within the gateway app.
In this example, there is no fallback endpoint or handler in the gateway application.
+However, there is one in another application, registered under localhost:9994.
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.
+In case of the request being forwarded to fallback, the Spring Cloud CircuitBreaker Gateway filter also provides the Throwable that has caused it.
+It is added to the ServerWebExchange as the ServerWebExchangeUtils.CIRCUITBREAKER_EXECUTION_EXCEPTION_ATTR attribute that can be used when handling the fallback within the gateway application.
For the external controller/handler scenario, headers can be added with exception details. +You can find more information on doing so in the FallbackHeaders GatewayFilter Factory section.
FallbackHeaders GatewayFilter FactoryThe FallbackHeaders factory allows you to add Hystrix or Spring Cloud CircuitBreaker execution exception details in headers of a request forwarded to
-a fallbackUri in an external application, like in the following scenario:
The FallbackHeaders factory lets you add Hystrix or Spring Cloud CircuitBreaker execution exception details in the headers of a request forwarded to a fallbackUri in an external application, as in the following scenario:
spring:
cloud:
@@ -1119,14 +1301,14 @@ a fallbackUri in an external application, like in the following sce
executionExceptionTypeHeaderName: Test-Header
In this example, after an execution exception occurs while running the circuit breaker, 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.
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:
+In this example, after an execution exception occurs while running the circuit breaker, the request is forwarded to the fallback endpoint or handler in an application running on localhost:9994.
+The headers with the exception type, message and (if available) root cause exception type and message are added to that request by the FallbackHeaders filter.
You can overwrite the names of the headers in the configuration by setting the values of the following arguments (shown with their default values):
For more information of circuit beakers and the Gateway see the Hystrix GatewayFilter Factory section or -Spring Cloud CircuitBreaker Factory section.
+For more information on circuit beakers and the gatewayc see the Hystrix GatewayFilter Factory section or Spring Cloud CircuitBreaker Factory section.
MapRequestHeader GatewayFilter FactoryThe MapRequestHeader GatewayFilter Factory takes 'fromHeader' and 'toHeader' parameters. It creates a new named header (toHeader) and the value is extracted out of an existing named header (fromHeader) from the incoming http request. If the input header does not exist then the filter has no impact. If the new named header already exists then it’s values will be augmented with the new values.
+The MapRequestHeader GatewayFilter factory takes fromHeader and toHeader parameters.
+It creates a new named header (toHeader), and the value is extracted out of an existing named header (fromHeader) from the incoming http request.
+If the input header does not exist, the filter has no impact.
+If the new named header already exists, its values are augmented with the new values.
+The following example configures a MapRequestHeader:
spring:
cloud:
@@ -1164,20 +1351,25 @@ their default values:
- id: map_request_header_route
uri: https://example.org
filters:
- - MapRequestHeader=Bar, X-Request-Foo
+ - MapRequestHeader=Blue, X-Request-Red
+This will add X-Request-Foo:<values> header to the downstream request’s with updated values from the incoming http request Bar header.
This adds X-Request-Red:<values> header to the downstream request with updated values from the incoming HTTP request’s Blue header.
PrefixPath GatewayFilter FactoryThe PrefixPath GatewayFilter Factory takes a single prefix parameter.
The PrefixPath GatewayFilter factory takes a single prefix parameter.
+The following example configures a PrefixPath GatewayFilter:
spring:
cloud:
@@ -1189,17 +1381,24 @@ their default values:
- PrefixPath=/mypath
This will prefix /mypath to the path of all matching requests. So a request to /hello, would be sent to /mypath/hello.
This will prefix /mypath to the path of all matching requests.
+So a request to /hello would be sent to /mypath/hello.
PreserveHostHeader GatewayFilter FactoryThe 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.
+The PreserveHostHeader GatewayFilter factory has no parameters.
+This filter sets a request attribute that the routing filter inspects to determine if the original host header should be sent, rather than the host header determined by the HTTP client.
+The following example configures a PreserveHostHeader GatewayFilter:
spring:
cloud:
@@ -1212,33 +1411,44 @@ their default values:
RequestRateLimiter GatewayFilter FactoryThe 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.
The RequestRateLimiter GatewayFilter factory 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.
This filter takes an optional keyResolver parameter and parameters specific to the rate limiter (see below).
This filter takes an optional keyResolver parameter and parameters specific to the rate limiter (described later in this section).
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 is a bean that implements the KeyResolver interface.
+In configuration, reference the bean by name using SpEL.
+#{@myKeyResolver} is a SpEL expression that references a bean named myKeyResolver.
+The following listing shows the KeyResolver interface:
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().
The KeyResolver interface lets pluggable strategies derive the key for limiting requests.
+In future milestone releases, there will be some KeyResolver implementations.
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 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 are denied.
+You can adjust this behavior by setting 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 - | - -
The RequestRateLimiter is not configurable with the "shortcut" notation. The following example below is invalid:
# INVALID SHORTCUT CONFIGURATION
spring.cloud.gateway.routes[0].filters[0]=RequestRateLimiter=2, 2, #{@userkeyresolver}
RateLimiterThe redis implementation is based off of work done at Stripe. It requires the use of the spring-boot-starter-data-redis-reactive Spring Boot starter.
The Redis implementation is based off of work done at Stripe.
+It requires the use of the spring-boot-starter-data-redis-reactive Spring Boot starter.
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.
The redis-rate-limiter.replenishRate is how many requests per second you want a user to be allowed to do, without any dropped requests.
+This is the rate at which the token bucket is filled.
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.
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 blocks all requests.
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).
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 two consecutive bursts will result in dropped requests (HTTP 429 - Too Many Requests).
+The following listing configures a redis-rate-limiter:
spring:
cloud:
@@ -1292,8 +1517,15 @@ spring.cloud.gateway.routes[0].filters[0]=RequestRateLimiter=2, 2, #{@userkeyres
redis-rate-limiter.burstCapacity: 20
The following example configures a KeyResolver in Java:
+@Bean
KeyResolver userKeyResolver() {
@@ -1301,14 +1533,22 @@ KeyResolver userKeyResolver() {
}
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).
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.
This defines a request rate limit of 10 per user. A burst of 20 is allowed, but, in the next second, only 10 requests are available.
+The KeyResolver is a simple one that gets the user request parameter (note that this is not recommended for production).
You can also define a rate limiter as a bean that implements the RateLimiter interface.
+In configuration, you can reference the bean by name using SpEL.
+#{@myRateLimiter} is a SpEL expression that references a bean with named myRateLimiter.
+The following listing defines a rate limiter that uses the KeyResolver defined in the previous listing:
spring:
cloud:
@@ -1325,13 +1565,21 @@ KeyResolver userKeyResolver() {
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 FactoryThe RedirectTo GatewayFilter factory takes two parameters, status and url.
+The status parameter should be a 300 series redirect HTTP code, such as 301.
+The url parameter should be a valid URL.
+This is the value of the Location header.
+The following listing configures a RedirectTo GatewayFilter:
spring:
cloud:
@@ -1343,55 +1591,62 @@ KeyResolver userKeyResolver() {
- RedirectTo=302, https://acme.org
This will send a status 302 with a Location:https://acme.org header to perform a redirect.
RemoveHopByHopHeadersFilter GatewayFilter FactoryThe RemoveHopByHopHeadersFilter GatewayFilter Factory removes headers from forwarded requests. The default list of headers that is removed comes from the IETF.
+The RemoveHopByHopHeadersFilter GatewayFilter Factory removes headers from forwarded requests.
+The default list of headers that is removed comes from the IETF.
Connection
+Connection
Keep-Alive
+Keep-Alive
Proxy-Authenticate
+Proxy-Authenticate
Proxy-Authorization
+Proxy-Authorization
TE
+TE
Trailer
+Trailer
Transfer-Encoding
+Transfer-Encoding
Upgrade
+Upgrade
To change this, set the spring.cloud.gateway.filter.remove-non-proxy-headers.headers property to the list of header names to remove.
To change the removed headers, set the spring.cloud.gateway.filter.remove-non-proxy-headers.headers property to the list of header names to remove.
RemoveRequestHeader GatewayFilter FactoryThe RemoveRequestHeader GatewayFilter Factory takes a name parameter. It is the name of the header to be removed.
The RemoveRequestHeader GatewayFilter factory takes a name parameter.
+It is the name of the header to be removed.
+The following listing configures a RemoveRequestHeader GatewayFilter:
spring:
cloud:
@@ -1403,17 +1658,23 @@ KeyResolver userKeyResolver() {
- RemoveRequestHeader=X-Request-Foo
This will remove the X-Request-Foo header before it is sent downstream.
This removes the X-Request-Foo header before it is sent downstream.
RemoveResponseHeader GatewayFilter FactoryThe RemoveResponseHeader GatewayFilter Factory takes a name parameter. It is the name of the header to be removed.
The RemoveResponseHeader GatewayFilter factory takes a name parameter.
+It is the name of the header to be removed.
+The following listing configures a RemoveResponseHeader GatewayFilter:
spring:
cloud:
@@ -1425,22 +1686,27 @@ KeyResolver userKeyResolver() {
- RemoveResponseHeader=X-Response-Foo
This will remove the X-Response-Foo header from the response before it is returned to the gateway client.
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.
To remove any kind of sensitive header, you should configure this filter for any routes for which you may want to do so.
+In addition, you can configure this filter once by using spring.cloud.gateway.default-filters and have it applied to all routes.
RemoveRequestParameter GatewayFilter FactoryThe RemoveRequestParameter GatewayFilter Factory takes a name parameter. It is the name of the query parameter to be removed.
The RemoveRequestParameter GatewayFilter factory takes a name parameter.
+It is the name of the query parameter to be removed.
+The following example configures a RemoveRequestParameter GatewayFilter:
spring:
cloud:
@@ -1449,20 +1715,26 @@ and have it applied to all routes.
- id: removerequestparameter_route
uri: https://example.org
filters:
- - RemoveRequestParameter=foo
+ - RemoveRequestParameter=red
+This will remove the foo parameter before it is sent downstream.
This will remove the red parameter before it is sent downstream.
RewritePath GatewayFilter FactoryThe 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.
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.
+The following listing configures a RewritePath GatewayFilter:
spring:
cloud:
@@ -1473,20 +1745,26 @@ and have it applied to all routes.
predicates:
- Path=/foo/**
filters:
- - RewritePath=/foo(?<segment>/?.*), $\{segment}
+ - RewritePath=/red(?<segment>/?.*), $\{segment}
+For a request path of /foo/bar, this will set the path to /bar before making the downstream request. Notice the $ Should be replaced with $\ because of the YAML spec.
For a request path of /red/blue, this sets the path to /blue before making the downstream request. Note that the $ should be replaced with $\ because of the YAML specification.
RewriteLocationResponseHeader GatewayFilter FactoryThe RewriteLocationResponseHeader GatewayFilter Factory modifies the value of Location response header, usually to get rid of backend specific details. It takes stripVersionMode, locationHeaderName, hostValue, and protocolsRegex parameters.
The RewriteLocationResponseHeader GatewayFilter factory modifies the value of the Location response header, usually to get rid of backend-specific details.
+It takes stripVersionMode, locationHeaderName, hostValue, and protocolsRegex parameters.
+The following listing configures a RewriteLocationResponseHeader GatewayFilter:
spring:
cloud:
@@ -1498,39 +1776,48 @@ and have it applied to all routes.
- RewriteLocationResponseHeader=AS_IN_REQUEST, Location, ,
For example, for a request POST api.example.com/some/object/name, Location response header value object-service.prod.example.net/v2/some/object/id will be rewritten as api.example.com/some/object/id.
Parameter stripVersionMode has the following possible values: NEVER_STRIP, AS_IN_REQUEST (default), ALWAYS_STRIP.
For example, for a request of POST api.example.com/some/object/name, the Location response header value of object-service.prod.example.net/v2/some/object/id is rewritten as api.example.com/some/object/id.
The stripVersionMode parameter has the following possible values: NEVER_STRIP, AS_IN_REQUEST (default), and ALWAYS_STRIP.
NEVER_STRIP - Version will not be stripped, even if the original request path contains no version
NEVER_STRIP: The version is not stripped, even if the original request path contains no version.
AS_IN_REQUEST - Version will be stripped only if the original request path contains no version
AS_IN_REQUEST The version is stripped only if the original request path contains no version.
ALWAYS_STRIP - Version will be stripped, even if the original request path contains version
ALWAYS_STRIP The version is always stripped, even if the original request path contains version.
Parameter hostValue, if provided, will be used to replace the host:port portion of the response Location header. If not provided, the value of the Host request header will be used.
The hostValue parameter, if provided, is used to replace the host:port portion of the response Location header.
+If it is not provided, the value of the Host request header is used.
Parameter protocolsRegex must be a valid regex String, against which the protocol name will be matched. If not matched, the filter will do nothing. Default is http|https|ftp|ftps.
The protocolsRegex parameter must be a valid regex String, against which the protocol name is matched.
+If it is not matched, the filter does nothing.
+The default is http|https|ftp|ftps.
RewriteResponseHeader GatewayFilter FactoryThe RewriteResponseHeader GatewayFilter Factory takes name, regexp, and replacement parameters. It uses Java regular expressions for a flexible way to rewrite the response header value.
The RewriteResponseHeader GatewayFilter factory takes name, regexp, and replacement parameters.
+It uses Java regular expressions for a flexible way to rewrite the response header value.
+The following example configures a RewriteResponseHeader GatewayFilter:
spring:
cloud:
@@ -1539,21 +1826,27 @@ and have it applied to all routes.
- id: rewriteresponseheader_route
uri: https://example.org
filters:
- - RewriteResponseHeader=X-Response-Foo, , password=[^&]+, password=***
+ - RewriteResponseHeader=X-Response-Red, , 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.
For a header value of /42?user=ford&password=omg!what&flag=true, it is set to /42?user=ford&password=***&flag=true after making the downstream request.
+You must use $\ to mean $ because of the YAML specification.
SaveSession GatewayFilter FactoryThe 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.
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 you need to ensure the session state has been saved before making the forwarded call.
+The following example configures a SaveSession GatewayFilter:
spring:
cloud:
@@ -1567,49 +1860,53 @@ using something like Spring
- 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.
+If you integrate Spring Security with Spring Session and want to ensure security details have been forwarded to the remote process, this is critical.
SecureHeaders GatewayFilter FactoryThe SecureHeaders GatewayFilter Factory adds a number of headers to the response at the recommendation from this blog post.
+The SecureHeaders GatewayFilter factory adds a number of headers to the response, per the recommendation made in this blog post.
The following headers (shown with their default values) are added:
X-Xss-Protection:1; mode=block
X-Xss-Protection:1 (mode=block)
Strict-Transport-Security:max-age=631138519
Strict-Transport-Security (max-age=631138519)
X-Frame-Options:DENY
X-Frame-Options (DENY)
X-Content-Type-Options:nosniff
X-Content-Type-Options (nosniff)
Referrer-Policy:no-referrer
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'
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-Download-Options (noopen)
X-Permitted-Cross-Domain-Policies:none
X-Permitted-Cross-Domain-Policies (none)
To change the default values set the appropriate property in the spring.cloud.gateway.filter.secure-headers namespace:
To change the default values, set the appropriate property in the spring.cloud.gateway.filter.secure-headers namespace.
+The following properties are available:
xss-protection-header
strict-transport-security
frame-options
content-type-options
referrer-policy
content-security-policy
download-options
permitted-cross-domain-policies
To disable the default values set the property spring.cloud.gateway.filter.secure-headers.disable with comma separated values.
| - - | --Need use lowercase and full name of secure headers. - | -
x-xss-protection
strict-transport-security
x-frame-options
spring.cloud.gateway.filter.secure-headers.disable=x-frame-options,strict-transport-security
To disable the default values set the spring.cloud.gateway.filter.secure-headers.disable property with comma-separated values.
+The following example shows how to do so:
spring.cloud.gateway.filter.secure-headers.disable=x-frame-options,strict-transport-security
+| + + | ++The lowercase full name of the secure header needs to be used to disable it.. + | +
SetPath GatewayFilter FactoryThe 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.
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.
+The following example configures a SetPath GatewayFilter:
spring:
cloud:
@@ -1701,22 +1981,27 @@ Need use lowercase and full name of secure headers.
- id: setpath_route
uri: https://example.org
predicates:
- - Path=/foo/{segment}
+ - Path=/red/{segment}
filters:
- SetPath=/{segment}
For a request path of /foo/bar, this will set the path to /bar before making the downstream request.
For a request path of /red/blue, this sets the path to /blue before making the downstream request.
SetRequestHeader GatewayFilter FactoryThe SetRequestHeader GatewayFilter Factory takes name and value parameters.
The SetRequestHeader GatewayFilter factory takes name and value parameters.
+The following listing configures a SetRequestHeader GatewayFilter:
spring:
cloud:
@@ -1725,17 +2010,24 @@ Need use lowercase and full name of secure headers.
- id: setrequestheader_route
uri: https://example.org
filters:
- - SetRequestHeader=X-Request-Foo, Bar
+ - SetRequestHeader=X-Request-Red, Blue
+This GatewayFilter replaces all headers with the given name, rather than adding. So if the downstream server responded with a X-Request-Foo:1234, this would be replaced with X-Request-Foo:Bar, which is what the downstream service would receive.
This GatewayFilter replaces (rather than adding) all headers with the given name.
+So, if the downstream server responded with a X-Request-Red:1234, this would be replaced with X-Request-Red:Blue, which is what the downstream service would receive.
SetRequestHeader is aware of URI variables used to match a path or host. URI variables may be used in the value and will be expanded at runtime.
+SetRequestHeader is aware of URI variables used to match a path or host.
+URI variables may be used in the value and are expanded at runtime.
+The following example configures an SetRequestHeader GatewayFilter that uses a variable:
spring:
cloud:
@@ -1750,13 +2042,18 @@ Need use lowercase and full name of secure headers.
The SetResponseHeader GatewayFilter Factory takes name and value parameters.
SetResponseHeader GatewayFilter FactoryThe SetResponseHeader GatewayFilter factory takes name and value parameters.
+The following listing configures a SetResponseHeader GatewayFilter:
spring:
cloud:
@@ -1765,17 +2062,24 @@ Need use lowercase and full name of secure headers.
- id: setresponseheader_route
uri: https://example.org
filters:
- - SetResponseHeader=X-Response-Foo, Bar
+ - SetResponseHeader=X-Response-Red, Blue
+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.
This GatewayFilter replaces (rather than adding) all headers with the given name.
+So, if the downstream server responded with a X-Response-Red:1234, this is replaced with X-Response-Red:Blue, which is what the gateway client would receive.
SetResponseHeader is aware of URI variables used to match a path or host. URI variables may be used in the value and will be expanded at runtime.
+SetResponseHeader is aware of URI variables used to match a path or host.
+URI variables may be used in the value and will be expanded at runtime.
+The following example configures an SetResponseHeader GatewayFilter that uses a variable:
spring:
cloud:
@@ -1790,13 +2094,20 @@ Need use lowercase and full name of secure headers.
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 FactoryThe SetStatus GatewayFilter factory takes a single parameter, status.
+It must be a valid Spring HttpStatus.
+It may be the integer value 404 or the string representation of the enumeration: NOT_FOUND.
+The following listing configures a SetStatus GatewayFilter:
spring:
cloud:
@@ -1812,14 +2123,19 @@ Need use lowercase and full name of secure headers.
- SetStatus=401
In either case, the HTTP status of the response will be set to 401.
+The SetStatus GatewayFilter can be configured to return the original HTTP status code from the proxied request in a header in the response. Header will be added to the response if configured using following property.
+In either case, the HTTP status of the response is set to 401.
You can configure the SetStatus GatewayFilter to return the original HTTP status code from the proxied request in a header in the response.
+The header is added to the response if configured with the following property:
spring:
cloud:
@@ -1829,13 +2145,19 @@ Need use lowercase and full name of secure headers.
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 FactoryThe StripPrefix GatewayFilter factory takes one parameter, parts.
+The parts parameter indicates the number of parts in the path to strip from the request before sending it downstream.
+The following listing configures a StripPrefix GatewayFilter:
spring:
cloud:
@@ -1849,63 +2171,71 @@ Need use lowercase and full name of secure headers.
- StripPrefix=2
When a request is made through the gateway to /name/bar/foo the request made to nameservice will look like nameservice/foo.
When a request is made through the gateway to /name/blue/red, the request made to nameservice looks like nameservice/red.
GatewayFilter FactoryThe Retry GatewayFilter Factory support following set of parameters:
+The Retry GatewayFilter factory supports the following parameters:
retries: the number of retries that should be attempted
retries: The number of retries that should be attempted.
statuses: the HTTP status codes that should be retried, represented using org.springframework.http.HttpStatus
statuses: The HTTP status codes that should be retried, represented by using org.springframework.http.HttpStatus.
methods: the HTTP methods that should be retried, represented using org.springframework.http.HttpMethod
methods: The HTTP methods that should be retried, represented by using org.springframework.http.HttpMethod.
series: the series of status codes to be retried, represented using org.springframework.http.HttpStatus.Series
series: The series of status codes to be retried, represented by using org.springframework.http.HttpStatus.Series.
exceptions: list of exceptions thrown that should be retried
exceptions: A list of thrown exceptions that should be retried.
backoff: configured exponential backoff for the retries. Retries are performed after a backoff interval of firstBackoff * (factor ^ n) where n is the iteration.
-If maxBackoff is configured, the maximum backoff applied will be limited to maxBackoff.
-If basedOnPreviousValue is true, backoff will be calculated using prevBackoff * factor.
backoff: The configured exponential backoff for the retries.
+Retries are performed after a backoff interval of firstBackoff * (factor ^ n), where n is the iteration.
+If maxBackoff is configured, the maximum backoff applied is limited to maxBackoff.
+If basedOnPreviousValue is true, the backoff is calculated byusing prevBackoff * factor.
The following defaults are configured for Retry filter if enabled:
The following defaults are configured for Retry filter, if enabled:
retries — 3 times
retries: Three times
series — 5XX series
series: 5XX series
methods — GET method
methods: GET method
exceptions — IOException and TimeoutException
exceptions: IOException and TimeoutException
backoff — disabled
backoff: disabled
The following listing configures a Retry GatewayFilter:
spring:
cloud:
@@ -1927,6 +2257,8 @@ If basedOnPreviousValue is true, backoff will be calculated using <
basedOnPreviousValue: false
| -The retry filter does not currently support retrying with a body (e.g. for POST or PUT requests with a body). +The retry filter does not currently support retrying with a body (for example, for POST or PUT requests with a body). |
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.
+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 (for example, through a Mono.error(ex) return value), which the retry filter can be configured to handle by retrying.
RequestSize GatewayFilter FactoryThe 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.
When the request size is greater than the permissible limit, the RequestSize GatewayFilter factory can restrict a request from reaching the downstream service.
+The filter takes a RequestSize parameter.
+It is the permissible size limit of the request defined in bytes.
+The following listing configures a RequestSize GatewayFilter:
spring:
cloud:
@@ -1974,11 +2313,19 @@ When using the retry filter with a forward: prefixed URL, the targe
maxSize: 5000000
The RequestSize GatewayFilter Factory set the response status as 413 Payload Too Large with a additional header errorMessage when 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 RequestSize GatewayFilter factory sets the response status as 413 Payload Too Large with an additional header errorMessage when the request is rejected due to size. The following example shows 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. +The default request size is set to five MB if not provided as a filter argument in the route definition. |
This filter is considered BETA and the API may change in the future
+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.
+You can use this filter to modify the request body before it is sent downstream by the gateway.
| -This filter can only be configured using the Java DSL +This filter can be configured only by using the Java DSL. |
The following listing shows how to modify a request body GatewayFilter:
@Bean
@@ -2045,13 +2406,24 @@ static class Hello {
This filter is considered BETA and the API may change in the future
+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.
+You can use this filter to modify the response body before it is sent back to the client.
| -This filter can only be configured using the Java DSL +This filter can be configured only by using the Java DSL. |
The following listing shows how to modify a response body GatewayFilter:
@Bean
@@ -2079,42 +2456,68 @@ public RouteLocator routes(RouteLocatorBuilder builder) {
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
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.
+The following listing defines a set of default filters:
spring:
cloud:
gateway:
default-filters:
- - AddResponseHeader=X-Response-Default-Foo, Default-Bar
+ - AddResponseHeader=X-Response-Default-Red, Default-Blue
- PrefixPath=/httpbin
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).
The GlobalFilter interface has the same signature as GatewayFilter.
+These are special filters that are conditionally applied to all routes.
| + + | ++This interface and its usage are subject to change in future milestone releases. + | +
GatewayFilter OrderingWhen 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.Ordered interface, which can be set by implementing the getOrder() method.
When a request matches a route, the filtering web handler adds 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.Ordered interface, which you can set by implementing the getOrder() method.
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.
+As Spring Cloud Gateway distinguishes between “pre” and “post” phases for filter logic execution (see How it Works), the filter with the highest precedence is the first in the “pre”-phase and the last in the “post”-phase.
The following listing configures a filter chain:
+@Bean
public GlobalFilter customFilter() {
@@ -2137,19 +2540,31 @@ public class CustomGlobalFilter implements GlobalFilter, Ordered {
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.
The ForwardRoutingFilter looks for a URI in the exchange attribute ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR.
+If the URL has a forward scheme (such as forward:///localendpoint), it uses the Spring DispatcherHandler to handle the request.
+The path part of the request URL is 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.
LoadBalancerClient FilterThe 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.
The LoadBalancerClientFilter looks for a URI in the exchange attribute named ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR.
+If the URL has a scheme of lb (such as lb://myservice), it uses the Spring Cloud LoadBalancerClient to resolve the name (myservice in this case) to an actual host and port and replaces 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 also looks in the ServerWebExchangeUtils.GATEWAY_SCHEME_PREFIX_ATTR attribute to see if it equals lb.
+If so, the same rules apply.
+The following listing configures a LoadBalancerClientFilter:
spring:
cloud:
@@ -2161,6 +2576,8 @@ public class CustomGlobalFilter implements GlobalFilter, Ordered {
- Path=/service/**
-By default when a service instance cannot be found in the LoadBalancer a 503 will be returned.
+By default, when a service instance cannot be found in the LoadBalancer, a 503 is 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.
+The isSecure value of the ServiceInstance returned from the LoadBalancer overrides
+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, the downstream request is 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 is stripped and the resulting scheme from the
+route URL overrides the ServiceInstance configuration.
|
ServiceInstance configuration.
LoadBalancerClientFilter uses a blocking Ribbon LoadBalancerClient under the hood.
+LoadBalancerClientFilter uses a blocking ribbon LoadBalancerClient under the hood.
We suggest you use ReactiveLoadBalancerClientFilter instead.
-You can switch to using it by setting the value of the spring.cloud.loadbalancer.ribbon.enabled to false.
+You can switch to it by setting the value of the spring.cloud.loadbalancer.ribbon.enabled to false.
ReactiveLoadBalancerClientFilterThe ReactiveLoadBalancerClientFilter 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 ReactorLoadBalancer 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.
The ReactiveLoadBalancerClientFilter looks for a URI in the exchange attribute named ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR.
+If the URL has a lb scheme (such as lb://myservice), it uses the Spring Cloud ReactorLoadBalancer to resolve the name (myservice in this example) to an actual host and port and replaces 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 also looks in the ServerWebExchangeUtils.GATEWAY_SCHEME_PREFIX_ATTR attribute to see if it equals lb.
+If so, the same rules apply.
+The following listing configures a ReactiveLoadBalancerClientFilter:
spring:
cloud:
@@ -2230,6 +2651,8 @@ The filter will also look in the ServerWebExchangeUtils.GATEWAY_SCHEME_PRE
- Path=/service/**
-By default when a service instance cannot be found by the ReactorLoadBalancer, a 503 will be returned.
-You can configure the Gateway to return a 404 by setting spring.cloud.gateway.loadbalancer.use404=true.
+By default, when a service instance cannot be found by the ReactorLoadBalancer, a 503 is returned.
+You can configure the gateway to return a 404 by setting spring.cloud.gateway.loadbalancer.use404=true.
|
404 by setting spri
-The isSecure value of the ServiceInstance returned from the ReactiveLoadBalancerClientFilter 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.
+The isSecure value of the ServiceInstance returned from the ReactiveLoadBalancerClientFilter overrides
+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, the downstream request is 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 is stripped and the resulting scheme from the route URL overrides the ServiceInstance configuration.
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)
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 also an experimental WebClientHttpRoutingFilter that performs the same function but does not require Netty.)
The NettyWriteResponseFilter runs if there is a Netty HttpClientResponse in the ServerWebExchangeUtils.CLIENT_RESPONSE_ATTR exchange 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)
The NettyWriteResponseFilter runs if there is a Netty HttpClientResponse in the ServerWebExchangeUtils.CLIENT_RESPONSE_ATTR exchange attribute.
+It runs after all other filters have completed and writes the proxy response back to the gateway client response.
+(There is also an experimental WebClientWriteResponseFilter that performs the same function but does not require Netty.)
RouteToRequestUrl FilterThe 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 there is a Route object in the ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR exchange attribute, the RouteToRequestUrlFilter runs.
+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:ws://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.
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.
If the URL located in the ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR exchange attribute has a ws or wss scheme, the websocket routing rilter runs. It uses the Spring WebSocket infrastructure to forward the websocket request downstream.
Websockets may be load-balanced by prefixing the URI with lb, such as lb:ws://serviceid.
You can load-balance websockets by prefixing the URI with lb, such as lb:ws://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. +If you use SockJS as a fallback over normal HTTP, you should configure a normal HTTP route as well as the websocket Route. |
The following listing configures a websocket routing filter:
+spring:
cloud:
@@ -2322,30 +2756,32 @@ If you are using SockJS as a fallback ov
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:
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:
routeId: The route id
routeId: The route ID.
routeUri: The URI that the API will be routed to
routeUri: The URI to which the API is routed.
outcome: Outcome as classified by HttpStatus.Series
outcome: The outcome, as classified by HttpStatus.Series.
status: Http Status of the request returned to the client
status: The HTTP status of the request returned to the client.
httpStatusCode: Http Status of the request returned to the client
httpStatusCode: The HTTP Status of the request returned to the client.
httpMethod: The Http method used for the request
httpMethod: The HTTP method used for the request.
micrometer-registry-prometheus as a project dependency.
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
+
After the gateway has routed a ServerWebExchange, it marks 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.
ServerWebExchangeUtils.isAlreadyRouted takes a ServerWebExchange object and checks if it has been "routed"
ServerWebExchangeUtils.isAlreadyRouted takes a ServerWebExchange object and checks if it has been “routed”.
ServerWebExchangeUtils.setAlreadyRouted takes a ServerWebExchange object and marks it as "routed"
ServerWebExchangeUtils.setAlreadyRouted takes a ServerWebExchange object and marks it as “routed”.
The Gateway can listen for requests on https by following the usual Spring server configuration. Example:
+The gateway can listen for requests on HTTPS by following the usual Spring server configuration. +The following example shows how to do so:
server:
ssl:
@@ -2404,11 +2843,16 @@ or check if an exchange has already been routed.
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:
You can route gateway routes to both HTTP and HTTPS backends. +If you are routing to an HTTPS backend, you can configure the gateway to trust all downstream certificates with the following configuration:
+spring:
cloud:
@@ -2418,11 +2862,16 @@ or check if an exchange has already been routed.
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:
Using an insecure trust manager is not suitable for production. +For a production deployment, you can configure the gateway with a set of known certificates that it can trust with the following configuration:
+spring:
cloud:
@@ -2434,16 +2883,23 @@ or check if an exchange has already been routed.
- 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).
+If the Spring Cloud Gateway is not provisioned with trusted certificates, the default trust store is used (which you can override by setting the javax.net.ssl.trustStore system property).
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):
+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. +You can configure these timeouts can be configured (defaults shown) as follows:
spring:
cloud:
@@ -2458,28 +2914,38 @@ or check if an exchange has already been routed.
Configuration for Spring Cloud Gateway is driven by a collection of RouteDefinitionLocators.
Configuration for Spring Cloud Gateway is driven by a collection of RouteDefinitionLocator instances.
+The following listing shows the definition of the RouteDefinitionLocator interface:
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:
+By default, a PropertiesRouteDefinitionLocator loads properties by using Spring Boot’s @ConfigurationProperties mechanism.
The earlier configuration examples all use a shortcut notation that uses positional arguments rather than named ones. +The following two examples are equivalent:
+spring:
cloud:
@@ -2497,19 +2963,23 @@ or check if an exchange has already been routed.
- 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 RouteDefinitionLocator implementations based off of Spring Data Repositories such as: Redis, MongoDB and Cassandra.
For some usages of the gateway, properties are adequate, but some production use cases benefit from loading configuration from an external source, such as a database. Future milestone versions will have RouteDefinitionLocator implementations based off of Spring Data Repositories, such as Redis, MongoDB, and Cassandra.
Additional parameters can be configured for each route using metadata:
+You can configure additional parameters for each route by using metadata, as follows:
spring:
cloud:
@@ -2524,9 +2994,13 @@ or check if an exchange has already been routed.
iAmNumber: 1
All metadata properties could be acquired from exchange:
You could acquire all metadata properties from an exchange, as follows:
+Route route = exchange.getAttribute(GATEWAY_ROUTE_ATTR);
@@ -2538,6 +3012,8 @@ route.getMetadata(someKey);
To allow for simple configuration in Java, there is a fluent API defined in the RouteLocatorBuilder bean.
To allow for simple configuration in Java, the RouteLocatorBuilder bean includes a fluent API.
+The following listing shows how it works:
// static imports from GatewayFilters and RoutePredicates
@Bean
@@ -2641,40 +3120,44 @@ public RouteLocator customRouteLocator(RouteLocatorBuilder builder, ThrottleGate
}
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 Predicate class.
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 Predicate class.
DiscoveryClient Route Definition LocatorThe Gateway can be configured to create routes based on services registered with a DiscoveryClient compatible service registry.
You can configure the gateway to create routes based on services registered with a DiscoveryClient compatible service registry.
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).
To enable this, set spring.cloud.gateway.discovery.locator.enabled=true and make sure a DiscoveryClient implementation (such as Netflix Eureka, Consul, or Zookeeper) is on the classpath and enabled.
DiscoveryClient RoutesBy default the Gateway defines a single predicate and filter for routes created via a DiscoveryClient.
By default, the fateway defines a single predicate and filter for routes created with 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.
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.
The default filter is a rewrite path filter with the regex /serviceId/(?<remaining>.*) and the replacement /${remaining}.
+This 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.
If you want to customize the predicates or filters used by the DiscoveryClient routes, set 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 shown earlier, if you want to retain that functionality.
+The following example shows what this looks like:
spring.cloud.gateway.discovery.locator.predicates[0].name: Path
spring.cloud.gateway.discovery.locator.predicates[0].args[pattern]: "'/'+serviceId+'/**'"
@@ -2691,17 +3174,33 @@ spring.cloud.gateway.discovery.locator.filters[1].args[replacement]: "'/${remain
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).
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:
+You can configure the logging system to have a separate access log file. The following example creates a Logback configuration:
<appender name="accessLog" class="ch.qos.logback.core.FileAppender">
<file>access_log.log</file>
@@ -2720,14 +3219,19 @@ spring.cloud.gateway.discovery.locator.filters[1].args[replacement]: "'/${remain
The gateway can be configured to control CORS behavior. The "global" CORS configuration is a map of URL patterns to Spring Framework CorsConfiguration.
You can configure the gateway to control CORS behavior. The “global” CORS configuration is a map of URL patterns to Spring Framework CorsConfiguration.
+The following example configures CORS:
spring:
cloud:
@@ -2740,11 +3244,14 @@ spring.cloud.gateway.discovery.locator.filters[1].args[replacement]: "'/${remain
- GET
In the example above, CORS requests will be allowed from requests that originate from docs.spring.io for all GET requested paths.
+To provide the same CORS configuration to requests that are not handled by some gateway route predicate, set the property spring.cloud.gateway.globalcors.add-to-simple-url-handler-mapping equal to true. This is useful when trying to support CORS preflight requests and your route predicate doesn’t evalute to true because the http method is options.
In the preceding example, CORS requests are allowed from requests that originate from docs.spring.io for all GET requested paths.
To provide the same CORS configuration to requests that are not handled by some gateway route predicate, set the spring.cloud.gateway.globalcors.add-to-simple-url-handler-mapping property to true.
+This is useful when you try to support CORS preflight requests and your route predicate does not evalute to true because the HTTP method is options.
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.
The /gateway actuator endpoint lets you monitor and interact with a Spring Cloud Gateway application.
+To be remotely accessible, the endpoint has to be enabled and exposed over HTTP or JMX in the application properties.
+The following listing shows how to do so:
management.endpoint.gateway.enabled=true # default value
management.endpoints.web.exposure.include=gateway
A new, more verbose format has been added to Gateway. This adds more detail to each route allowing to view the predicates and filters associated to each route along with any configuration that is available.
-/actuator/gateway/routes
A new, more verbose format has been added to Spring Cloud Gateway.
+It adds more detail to each route, letting you view the predicates and filters associated with each route along with any configuration that is available.
+The following example configures /actuator/gateway/routes:
[
@@ -2786,26 +3300,47 @@ management.endpoints.web.exposure.include=gateway
]
This feature is enabled by default. To disable it, set the following property:
spring.cloud.gateway.actuator.verbose.enabled=false
This will default to true in a future release.
+This will default to true in a future release.
This section details how to retrieve route filters, including:
+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:
{
@@ -2820,15 +3355,21 @@ management.endpoints.web.exposure.include=gateway
}
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.
The response contains the details of the global filters that are in place.
+For each global filter, there is a string representation of the filter object (for example, org.springframework.cloud.gateway.filter.LoadBalancerClientFilter@77856cc5) and the corresponding order in the filter chain.}
To retrieve the GatewayFilter factories applied to routes, make a GET request to /actuator/gateway/routefilters. The resulting response is similar to the following:
To retrieve the GatewayFilter factories applied to routes, make a GET request to /actuator/gateway/routefilters.
+The resulting response is similar to the following:
{
@@ -2838,22 +3379,30 @@ management.endpoints.web.exposure.include=gateway
}
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.
The response contains the details of the GatewayFilter factories applied to any particular route.
+For each factory there is a string representation of the corresponding object (for example, [SecureHeadersGatewayFilterFactory@fceab5d configClass = Object]).
+Note that the null value is due to an incomplete implementation of the endpoint controller, because it tries to set the order of the object in the filter chain, which does not apply to a GatewayFilter factory object.
To clear the routes cache, make a POST request to /actuator/gateway/refresh. The request returns a 200 without response body.
To clear the routes cache, make a POST request to /actuator/gateway/refresh.
+The request returns a 200 without a response body.
To retrieve the routes defined in the gateway, make a GET request to /actuator/gateway/routes. The resulting response is similar to the following:
To retrieve the routes defined in the gateway, make a GET request to /actuator/gateway/routes.
+The resulting response is similar to the following:
[{
@@ -2876,8 +3425,11 @@ management.endpoints.web.exposure.include=gateway
}]
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 response contains the details of all the routes defined in the gateway. +The following table describes the structure of each element (each is a route) of the response:
|
String |
-The route id. |
+The route ID. |
|
@@ -2906,7 +3458,7 @@ management.endpoints.web.exposure.include=gateway
|||
|
Array |
-The GatewayFilter factories applied to the route. |
+The |
|
@@ -2917,10 +3469,13 @@ management.endpoints.web.exposure.include=gateway
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:
To retrieve information about a single route, make a GET request to /actuator/gateway/routes/{id} (for example, /actuator/gateway/routes/first_route).
+The resulting response is similar to the following:
{
@@ -2935,8 +3490,10 @@ management.endpoints.web.exposure.include=gateway
}]
The following table describes the structure of the response.
+The following table describes the structure of the response:
|
String |
-The route id. |
+The route ID. |
|
@@ -2981,18 +3538,18 @@ management.endpoints.web.exposure.include=gateway
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 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 Retrieving Information about a Particular Route).
To delete a route, make a DELETE request to /gateway/routes/{id_route_to_delete}.
The table below summarises the Spring Cloud Gateway actuator endpoints. Note that each endpoint has /actuator/gateway as the base-path.
The folloiwng table below summarizes the Spring Cloud Gateway actuator endpoints (note that each endpoint has /actuator/gateway as the base-path):
|
GET |
-Displays the list of GatewayFilter factories applied to a particular route. |
+Displays the list of |
|
@@ -3036,12 +3593,12 @@ management.endpoints.web.exposure.include=gateway
|||
|
POST |
-Add a new route to the gateway. |
+Adds a new route to the gateway. |
|
DELETE |
-Remove an existing route from the gateway. |
+Removes an existing route from the gateway. |
This section covers common problems that may arise when you use Spring Cloud Gateway.
+Below are some useful loggers that contain valuable trouble shooting infomration at the DEBUG and TRACE levels.
The following loggers may contain valuable troubleshooting information at the DEBUG and TRACE levels:
The Reactor Netty HttpClient and HttpServer can have wiretap enabled. When combined
-with setting the reactor.netty log level to DEBUG or TRACE will enable logging of
-information such as headers and bodies sent and received across the wire. To enable this,
-set spring.cloud.gateway.httpserver.wiretap=true and/or
-spring.cloud.gateway.httpclient.wiretap=true for the HttpServer and HttpClient
-respectively.
The Reactor Netty HttpClient and HttpServer can have wiretap enabled.
+When combined with setting the reactor.netty log level to DEBUG or TRACE, it enables the logging of information, such as headers and bodies sent and received across the wire.
+To enable wiretap, set spring.cloud.gateway.httpserver.wiretap=true or spring.cloud.gateway.httpclient.wiretap=true for the HttpServer and HttpClient, respectively.
In order to write a GatewayFilter you will need to implement GatewayFilterFactory. There is an abstract class called AbstractGatewayFilterFactory which you can extend.
To write a GatewayFilter, you must implement GatewayFilterFactory.
+You can extend an abstract class called AbstractGatewayFilterFactory.
+The following examples show how to do so:
public class PreGatewayFilterFactory extends AbstractGatewayFilterFactory<PreGatewayFilterFactory.Config> {
@@ -3165,14 +3726,19 @@ respectively.
In order to write a custom global filter, you will need to implement GlobalFilter interface. This will apply the filter to all requests.
To write a custom global filter, you must implement GlobalFilter interface.
+This applies the filter to all requests.
Example of how to set up a Global Pre and Post filter, respectively
+The following examples show how to set up global pre and post filters, respectively:
@Bean
@@ -3203,6 +3769,8 @@ public GlobalFilter customGlobalPostFilter() {
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).
Spring Cloud Gateway provides a utility object called ProxyExchange.
+You can use it inside a regular Spring web handler as a method parameter.
+It supports basic downstream HTTP exchanges through methods that mirror the HTTP verbs.
+With MVC, it also supports forwarding to a local handler through the forward() method.
+To use the ProxyExchange, 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):
+The following MVC example proxies a request to /test downstream to a remote server:
@RestController
@@ -3237,9 +3811,13 @@ public class GatewaySampleApplication {
}
The same thing with Webflux:
The following example does the same thing with Webflux:
+@RestController
@@ -3257,9 +3835,14 @@ public class GatewaySampleApplication {
}
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:
Convenience methods on the ProxyExchange 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/**")
@@ -3269,17 +3852,22 @@ public ResponseEntity<?> proxyPath(ProxyExchange<byte[]> proxy) thro
}
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.
All the features of Spring MVC and Webflux are available to gateway handler methods.
+As a result, 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.
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.
You can add headers to the downstream response by using the header() methods on ProxyExchange.
First class support is provided for "sensitive" headers ("cookie" and "authorization" by default) which are not passed downstream, and for "proxy" headers (x-forwarded-*).
You can also manipulate response headers (and anything else you like in the response) by adding a mapper to the get() method (and other methods).
+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 (by default, cookie and authorization), which are not passed downstream, and for “proxy” (x-forwarded-*) headers.
To see the list of all Spring Cloud Gateway related configuration properties please check the Appendix page.
+To see the list of all Spring Cloud Gateway related configuration properties, see the appendix.