From 5ffb0afe4ff15e218e8664c0920207d02b12417d Mon Sep 17 00:00:00 2001 From: buildmaster Date: Thu, 15 Nov 2018 17:01:38 +0000 Subject: [PATCH] Sync docs from master to gh-pages --- multi/multi__gatewayfilter_factories.html | 84 +++++++++++++++++----- multi/multi_spring-cloud-gateway.html | 2 +- single/spring-cloud-gateway.html | 86 ++++++++++++++++++----- spring-cloud-gateway.xml | 85 +++++++++++++++++++++- 4 files changed, 220 insertions(+), 37 deletions(-) diff --git a/multi/multi__gatewayfilter_factories.html b/multi/multi__gatewayfilter_factories.html index 4094996f..da938750 100644 --- a/multi/multi__gatewayfilter_factories.html +++ b/multi/multi__gatewayfilter_factories.html @@ -27,7 +27,7 @@ uri: http://example.org filters: - AddResponseHeader=X-Response-Foo, Bar

-

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

5.4 Hystrix GatewayFilter Factory

Hystrix is a library from Netflix that implements the circuit breaker pattern. +

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

5.4 Hystrix GatewayFilter Factory

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

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

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

application.yml. 

spring:
   cloud:
@@ -52,9 +52,59 @@ The Hystrix GatewayFilter allows you to introduce circuit breakers to your gatew
             name: fallbackcmd
             fallbackUri: forward:/incaseoffailureusethis
         - RewritePath=/consumingserviceendpoint, /backingserviceendpoint

-

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

Hystrix 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.

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

application.yml.  +

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.

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:

application.yml.  +

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

+

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

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.

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

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

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

application.yml. 

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

-

5.5 PrefixPath GatewayFilter Factory

The PrefixPath GatewayFilter Factory takes a single prefix parameter.

application.yml.  +

5.5 FallbackHeaders GatewayFilter Factory

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

application.yml.  +

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

+

In this example, after an execution exception occurs while running the HystrixCommand, the request will be forwarde 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:

  • executionExceptionTypeHeaderName ("Execution-Exception-Type")
  • executionExceptionMessageHeaderName ("Execution-Exception-Message")
  • rootCauseExceptionTypeHeaderName ("Root-Cause-Exception-Type")
  • rootCauseExceptionMessageHeaderName ("Root-Cause-Exception-Message")

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

5.6 PrefixPath GatewayFilter Factory

The PrefixPath GatewayFilter Factory takes a single prefix parameter.

application.yml. 

spring:
   cloud:
     gateway:
@@ -63,7 +113,7 @@ The Hystrix GatewayFilter allows you to introduce circuit breakers to your gatew
         uri: http://example.org
         filters:
         - PrefixPath=/mypath

-

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

5.6 PreserveHostHeader GatewayFilter Factory

The PreserveHostHeader GatewayFilter Factory has not 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.

application.yml.  +

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

5.7 PreserveHostHeader GatewayFilter Factory

The PreserveHostHeader GatewayFilter Factory has not 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.

application.yml. 

spring:
   cloud:
     gateway:
@@ -72,14 +122,14 @@ The Hystrix GatewayFilter allows you to introduce circuit breakers to your gatew
         uri: http://example.org
         filters:
         - PreserveHostHeader

-

5.7 RequestRateLimiter GatewayFilter Factory

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

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

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.java.  +

5.8 RequestRateLimiter GatewayFilter Factory

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

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

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.java. 

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

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

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

[Note]Note

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

application.properties. 

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

-

5.7.1 Redis RateLimiter

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.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.

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

application.yml.  +

5.8.1 Redis RateLimiter

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.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.

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

application.yml. 

spring:
   cloud:
     gateway:
@@ -108,7 +158,7 @@ KeyResolver userKeyResolver() {
           args:
             rate-limiter: "#{@myRateLimiter}"
             key-resolver: "#{@userKeyResolver}"

-

5.8 RedirectTo GatewayFilter Factory

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

application.yml.  +

5.9 RedirectTo GatewayFilter Factory

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

application.yml. 

spring:
   cloud:
     gateway:
@@ -117,7 +167,7 @@ KeyResolver userKeyResolver() {
         uri: http://example.org
         filters:
         - RedirectTo=302, http://acme.org

-

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

5.9 RemoveNonProxyHeaders GatewayFilter Factory

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

The default removed headers are:

  • Connection
  • Keep-Alive
  • Proxy-Authenticate
  • Proxy-Authorization
  • TE
  • Trailer
  • Transfer-Encoding
  • Upgrade

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

5.10 RemoveRequestHeader GatewayFilter Factory

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

application.yml.  +

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

5.10 RemoveNonProxyHeaders GatewayFilter Factory

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

The default removed headers are:

  • Connection
  • Keep-Alive
  • Proxy-Authenticate
  • Proxy-Authorization
  • TE
  • Trailer
  • Transfer-Encoding
  • Upgrade

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

5.11 RemoveRequestHeader GatewayFilter Factory

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

application.yml. 

spring:
   cloud:
     gateway:
@@ -126,7 +176,7 @@ KeyResolver userKeyResolver() {
         uri: http://example.org
         filters:
         - RemoveRequestHeader=X-Request-Foo

-

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

5.11 RemoveResponseHeader GatewayFilter Factory

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

application.yml.  +

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

5.12 RemoveResponseHeader GatewayFilter Factory

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

application.yml. 

spring:
   cloud:
     gateway:
@@ -135,7 +185,7 @@ KeyResolver userKeyResolver() {
         uri: http://example.org
         filters:
         - RemoveResponseHeader=X-Response-Foo

-

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

5.12 RewritePath GatewayFilter Factory

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

application.yml.  +

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

5.13 RewritePath GatewayFilter Factory

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

application.yml. 

spring:
   cloud:
     gateway:
@@ -146,7 +196,7 @@ KeyResolver userKeyResolver() {
         - Path=/foo/**
         filters:
         - RewritePath=/foo/(?<segment>.*), /$\{segment}

-

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

5.13 SaveSession GatewayFilter Factory

The SaveSession GatewayFilter Factory forces a WebSession::save operation before forwarding the call downstream. This is of particular use when +

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

5.14 SaveSession GatewayFilter Factory

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

application.yml. 

spring:
   cloud:
@@ -158,7 +208,7 @@ using something like         - Path=/foo/**
         filters:
         - SaveSession

-

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

5.14 SecureHeaders GatewayFilter Factory

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

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

  • X-Xss-Protection:1; mode=block
  • Strict-Transport-Security:max-age=631138519
  • X-Frame-Options:DENY
  • X-Content-Type-Options:nosniff
  • Referrer-Policy:no-referrer
  • Content-Security-Policy:default-src 'self' https:; font-src 'self' https: data:; img-src 'self' https: data:; object-src 'none'; script-src https:; style-src 'self' https: 'unsafe-inline'
  • X-Download-Options:noopen
  • X-Permitted-Cross-Domain-Policies:none

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

Property to change:

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

5.15 SetPath GatewayFilter Factory

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

application.yml.  +

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.

5.15 SecureHeaders GatewayFilter Factory

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

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

  • X-Xss-Protection:1; mode=block
  • Strict-Transport-Security:max-age=631138519
  • X-Frame-Options:DENY
  • X-Content-Type-Options:nosniff
  • Referrer-Policy:no-referrer
  • Content-Security-Policy:default-src 'self' https:; font-src 'self' https: data:; img-src 'self' https: data:; object-src 'none'; script-src https:; style-src 'self' https: 'unsafe-inline'
  • X-Download-Options:noopen
  • X-Permitted-Cross-Domain-Policies:none

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

Property to change:

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

5.16 SetPath GatewayFilter Factory

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

application.yml. 

spring:
   cloud:
     gateway:
@@ -169,7 +219,7 @@ using something like         - Path=/foo/{segment}
         filters:
         - SetPath=/{segment}

-

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

5.16 SetResponseHeader GatewayFilter Factory

The SetResponseHeader GatewayFilter Factory takes name and value parameters.

application.yml.  +

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

5.17 SetResponseHeader GatewayFilter Factory

The SetResponseHeader GatewayFilter Factory takes name and value parameters.

application.yml. 

spring:
   cloud:
     gateway:
@@ -178,7 +228,7 @@ using something like         uri: http://example.org
         filters:
         - SetResponseHeader=X-Response-Foo, Bar

-

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

5.17 SetStatus GatewayFilter Factory

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

application.yml.  +

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.

5.18 SetStatus GatewayFilter Factory

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

application.yml. 

spring:
   cloud:
     gateway:
@@ -191,7 +241,7 @@ using something like         uri: http://example.org
         filters:
         - SetStatus=401

-

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

5.18 StripPrefix GatewayFilter Factory

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

application.yml.  +

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

5.19 StripPrefix GatewayFilter Factory

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

application.yml. 

spring:
   cloud:
     gateway:
@@ -202,7 +252,7 @@ using something like         - Path=/name/**
         filters:
         - StripPrefix=2

-

When a request is made through the gateway to /name/bar/foo the request made to nameservice will look like http://nameservice/foo.

5.19 Retry GatewayFilter Factory

The Retry GatewayFilter Factory takes retries, statuses, methods, and series as parameters.

  • retries: the number of retries that should be attempted
  • statuses: the HTTP status codes that should be retried, represented using org.springframework.http.HttpStatus
  • methods: the HTTP methods that should be retried, represented using org.springframework.http.HttpMethod
  • series: the series of status codes to be retried, represented using org.springframework.http.HttpStatus.Series

application.yml.  +

When a request is made through the gateway to /name/bar/foo the request made to nameservice will look like http://nameservice/foo.

5.20 Retry GatewayFilter Factory

The Retry GatewayFilter Factory takes retries, statuses, methods, and series as parameters.

  • retries: the number of retries that should be attempted
  • statuses: the HTTP status codes that should be retried, represented using org.springframework.http.HttpStatus
  • methods: the HTTP methods that should be retried, represented using org.springframework.http.HttpMethod
  • series: the series of status codes to be retried, represented using org.springframework.http.HttpStatus.Series

application.yml. 

spring:
   cloud:
     gateway:
@@ -216,7 +266,7 @@ using something like           args:
             retries: 3
             statuses: BAD_GATEWAY

-

[Note]Note

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

5.20 RequestSize GatewayFilter Factory

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

application.yml.  +

[Note]Note

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

5.21 RequestSize GatewayFilter Factory

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

application.yml. 

spring:
   cloud:
     gateway:
diff --git a/multi/multi_spring-cloud-gateway.html b/multi/multi_spring-cloud-gateway.html
index 81cb8919..89409eda 100644
--- a/multi/multi_spring-cloud-gateway.html
+++ b/multi/multi_spring-cloud-gateway.html
@@ -1,3 +1,3 @@
 
       
-   Spring Cloud Gateway

Spring Cloud Gateway


Table of Contents

1. How to Include Spring Cloud Gateway
2. Glossary
3. How It Works
4. Route Predicate Factories
4.1. After Route Predicate Factory
4.2. Before Route Predicate Factory
4.3. Between Route Predicate Factory
4.4. Cookie Route Predicate Factory
4.5. Header Route Predicate Factory
4.6. Host Route Predicate Factory
4.7. Method Route Predicate Factory
4.8. Path Route Predicate Factory
4.9. Query Route Predicate Factory
4.10. RemoteAddr Route Predicate Factory
4.10.1. Modifying the way remote addresses are resolved
5. GatewayFilter Factories
5.1. AddRequestHeader GatewayFilter Factory
5.2. AddRequestParameter GatewayFilter Factory
5.3. AddResponseHeader GatewayFilter Factory
5.4. Hystrix GatewayFilter Factory
5.5. PrefixPath GatewayFilter Factory
5.6. PreserveHostHeader GatewayFilter Factory
5.7. RequestRateLimiter GatewayFilter Factory
5.7.1. Redis RateLimiter
5.8. RedirectTo GatewayFilter Factory
5.9. RemoveNonProxyHeaders GatewayFilter Factory
5.10. RemoveRequestHeader GatewayFilter Factory
5.11. RemoveResponseHeader GatewayFilter Factory
5.12. RewritePath GatewayFilter Factory
5.13. SaveSession GatewayFilter Factory
5.14. SecureHeaders GatewayFilter Factory
5.15. SetPath GatewayFilter Factory
5.16. SetResponseHeader GatewayFilter Factory
5.17. SetStatus GatewayFilter Factory
5.18. StripPrefix GatewayFilter Factory
5.19. Retry GatewayFilter Factory
5.20. RequestSize GatewayFilter Factory
6. Global Filters
6.1. Combined Global Filter and GatewayFilter Ordering
6.2. Forward Routing Filter
6.3. LoadBalancerClient Filter
6.4. Netty Routing Filter
6.5. Netty Write Response Filter
6.6. RouteToRequestUrl Filter
6.7. Websocket Routing Filter
6.8. Gateway Metrics Filter
6.9. Making An Exchange As Routed
7. TLS / SSL
7.1. TLS Handshake
8. Configuration
8.1. Fluent Java Routes API
8.2. DiscoveryClient Route Definition Locator
9. Reactor Netty Access Logs
10. CORS Configuration
11. Actuator API
12. Developer Guide
12.1. Writing Custom Route Predicate Factories
12.2. Writing Custom GatewayFilter Factories
12.3. Writing Custom Global Filters
12.4. Writing Custom Route Locators and Writers
13. Building a Simple Gateway Using Spring MVC or Webflux
\ No newline at end of file + Spring Cloud Gateway

Spring Cloud Gateway


Table of Contents

1. How to Include Spring Cloud Gateway
2. Glossary
3. How It Works
4. Route Predicate Factories
4.1. After Route Predicate Factory
4.2. Before Route Predicate Factory
4.3. Between Route Predicate Factory
4.4. Cookie Route Predicate Factory
4.5. Header Route Predicate Factory
4.6. Host Route Predicate Factory
4.7. Method Route Predicate Factory
4.8. Path Route Predicate Factory
4.9. Query Route Predicate Factory
4.10. RemoteAddr Route Predicate Factory
4.10.1. Modifying the way remote addresses are resolved
5. GatewayFilter Factories
5.1. AddRequestHeader GatewayFilter Factory
5.2. AddRequestParameter GatewayFilter Factory
5.3. AddResponseHeader GatewayFilter Factory
5.4. Hystrix GatewayFilter Factory
5.5. FallbackHeaders GatewayFilter Factory
5.6. PrefixPath GatewayFilter Factory
5.7. PreserveHostHeader GatewayFilter Factory
5.8. RequestRateLimiter GatewayFilter Factory
5.8.1. Redis RateLimiter
5.9. RedirectTo GatewayFilter Factory
5.10. RemoveNonProxyHeaders GatewayFilter Factory
5.11. RemoveRequestHeader GatewayFilter Factory
5.12. RemoveResponseHeader GatewayFilter Factory
5.13. RewritePath GatewayFilter Factory
5.14. SaveSession GatewayFilter Factory
5.15. SecureHeaders GatewayFilter Factory
5.16. SetPath GatewayFilter Factory
5.17. SetResponseHeader GatewayFilter Factory
5.18. SetStatus GatewayFilter Factory
5.19. StripPrefix GatewayFilter Factory
5.20. Retry GatewayFilter Factory
5.21. RequestSize GatewayFilter Factory
6. Global Filters
6.1. Combined Global Filter and GatewayFilter Ordering
6.2. Forward Routing Filter
6.3. LoadBalancerClient Filter
6.4. Netty Routing Filter
6.5. Netty Write Response Filter
6.6. RouteToRequestUrl Filter
6.7. Websocket Routing Filter
6.8. Gateway Metrics Filter
6.9. Making An Exchange As Routed
7. TLS / SSL
7.1. TLS Handshake
8. Configuration
8.1. Fluent Java Routes API
8.2. DiscoveryClient Route Definition Locator
9. Reactor Netty Access Logs
10. CORS Configuration
11. Actuator API
12. Developer Guide
12.1. Writing Custom Route Predicate Factories
12.2. Writing Custom GatewayFilter Factories
12.3. Writing Custom Global Filters
12.4. Writing Custom Route Locators and Writers
13. Building a Simple Gateway Using Spring MVC or Webflux
\ No newline at end of file diff --git a/single/spring-cloud-gateway.html b/single/spring-cloud-gateway.html index a88362fa..5b9e2f95 100644 --- a/single/spring-cloud-gateway.html +++ b/single/spring-cloud-gateway.html @@ -1,6 +1,6 @@ - Spring Cloud Gateway

Spring Cloud Gateway


Table of Contents

1. How to Include Spring Cloud Gateway
2. Glossary
3. How It Works
4. Route Predicate Factories
4.1. After Route Predicate Factory
4.2. Before Route Predicate Factory
4.3. Between Route Predicate Factory
4.4. Cookie Route Predicate Factory
4.5. Header Route Predicate Factory
4.6. Host Route Predicate Factory
4.7. Method Route Predicate Factory
4.8. Path Route Predicate Factory
4.9. Query Route Predicate Factory
4.10. RemoteAddr Route Predicate Factory
4.10.1. Modifying the way remote addresses are resolved
5. GatewayFilter Factories
5.1. AddRequestHeader GatewayFilter Factory
5.2. AddRequestParameter GatewayFilter Factory
5.3. AddResponseHeader GatewayFilter Factory
5.4. Hystrix GatewayFilter Factory
5.5. PrefixPath GatewayFilter Factory
5.6. PreserveHostHeader GatewayFilter Factory
5.7. RequestRateLimiter GatewayFilter Factory
5.7.1. Redis RateLimiter
5.8. RedirectTo GatewayFilter Factory
5.9. RemoveNonProxyHeaders GatewayFilter Factory
5.10. RemoveRequestHeader GatewayFilter Factory
5.11. RemoveResponseHeader GatewayFilter Factory
5.12. RewritePath GatewayFilter Factory
5.13. SaveSession GatewayFilter Factory
5.14. SecureHeaders GatewayFilter Factory
5.15. SetPath GatewayFilter Factory
5.16. SetResponseHeader GatewayFilter Factory
5.17. SetStatus GatewayFilter Factory
5.18. StripPrefix GatewayFilter Factory
5.19. Retry GatewayFilter Factory
5.20. RequestSize GatewayFilter Factory
6. Global Filters
6.1. Combined Global Filter and GatewayFilter Ordering
6.2. Forward Routing Filter
6.3. LoadBalancerClient Filter
6.4. Netty Routing Filter
6.5. Netty Write Response Filter
6.6. RouteToRequestUrl Filter
6.7. Websocket Routing Filter
6.8. Gateway Metrics Filter
6.9. Making An Exchange As Routed
7. TLS / SSL
7.1. TLS Handshake
8. Configuration
8.1. Fluent Java Routes API
8.2. DiscoveryClient Route Definition Locator
9. Reactor Netty Access Logs
10. CORS Configuration
11. Actuator API
12. Developer Guide
12.1. Writing Custom Route Predicate Factories
12.2. Writing Custom GatewayFilter Factories
12.3. Writing Custom Global Filters
12.4. Writing Custom Route Locators and Writers
13. Building a Simple Gateway Using Spring MVC or Webflux

2.1.0.BUILD-SNAPSHOT

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

1. How to Include Spring Cloud Gateway

To include Spring Cloud Gateway in your project use the starter with group org.springframework.cloud + Spring Cloud Gateway

Spring Cloud Gateway


Table of Contents

1. How to Include Spring Cloud Gateway
2. Glossary
3. How It Works
4. Route Predicate Factories
4.1. After Route Predicate Factory
4.2. Before Route Predicate Factory
4.3. Between Route Predicate Factory
4.4. Cookie Route Predicate Factory
4.5. Header Route Predicate Factory
4.6. Host Route Predicate Factory
4.7. Method Route Predicate Factory
4.8. Path Route Predicate Factory
4.9. Query Route Predicate Factory
4.10. RemoteAddr Route Predicate Factory
4.10.1. Modifying the way remote addresses are resolved
5. GatewayFilter Factories
5.1. AddRequestHeader GatewayFilter Factory
5.2. AddRequestParameter GatewayFilter Factory
5.3. AddResponseHeader GatewayFilter Factory
5.4. Hystrix GatewayFilter Factory
5.5. FallbackHeaders GatewayFilter Factory
5.6. PrefixPath GatewayFilter Factory
5.7. PreserveHostHeader GatewayFilter Factory
5.8. RequestRateLimiter GatewayFilter Factory
5.8.1. Redis RateLimiter
5.9. RedirectTo GatewayFilter Factory
5.10. RemoveNonProxyHeaders GatewayFilter Factory
5.11. RemoveRequestHeader GatewayFilter Factory
5.12. RemoveResponseHeader GatewayFilter Factory
5.13. RewritePath GatewayFilter Factory
5.14. SaveSession GatewayFilter Factory
5.15. SecureHeaders GatewayFilter Factory
5.16. SetPath GatewayFilter Factory
5.17. SetResponseHeader GatewayFilter Factory
5.18. SetStatus GatewayFilter Factory
5.19. StripPrefix GatewayFilter Factory
5.20. Retry GatewayFilter Factory
5.21. RequestSize GatewayFilter Factory
6. Global Filters
6.1. Combined Global Filter and GatewayFilter Ordering
6.2. Forward Routing Filter
6.3. LoadBalancerClient Filter
6.4. Netty Routing Filter
6.5. Netty Write Response Filter
6.6. RouteToRequestUrl Filter
6.7. Websocket Routing Filter
6.8. Gateway Metrics Filter
6.9. Making An Exchange As Routed
7. TLS / SSL
7.1. TLS Handshake
8. Configuration
8.1. Fluent Java Routes API
8.2. DiscoveryClient Route Definition Locator
9. Reactor Netty Access Logs
10. CORS Configuration
11. Actuator API
12. Developer Guide
12.1. Writing Custom Route Predicate Factories
12.2. Writing Custom GatewayFilter Factories
12.3. Writing Custom Global Filters
12.4. Writing Custom Route Locators and Writers
13. Building a Simple Gateway Using Spring MVC or Webflux

2.1.0.BUILD-SNAPSHOT

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

1. How to Include Spring Cloud Gateway

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

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

[Important]Important

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

2. Glossary

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

3. How It Works

Spring Cloud Gateway Diagram

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

[Note]Note

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

4. Route Predicate Factories

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

4.1 After Route Predicate Factory

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

application.yml. 

spring:
@@ -144,7 +144,7 @@ If two hops of trusted infrastructure are required before Spring Cloud Gateway i
         uri: http://example.org
         filters:
         - AddResponseHeader=X-Response-Foo, Bar

-

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

5.4 Hystrix GatewayFilter Factory

Hystrix is a library from Netflix that implements the circuit breaker pattern. +

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

5.4 Hystrix GatewayFilter Factory

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

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

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

application.yml. 

spring:
   cloud:
@@ -169,9 +169,59 @@ The Hystrix GatewayFilter allows you to introduce circuit breakers to your gatew
             name: fallbackcmd
             fallbackUri: forward:/incaseoffailureusethis
         - RewritePath=/consumingserviceendpoint, /backingserviceendpoint

-

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

Hystrix 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.

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

application.yml.  +

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.

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:

application.yml.  +

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

+

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

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.

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

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

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

application.yml. 

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

-

5.5 PrefixPath GatewayFilter Factory

The PrefixPath GatewayFilter Factory takes a single prefix parameter.

application.yml.  +

5.5 FallbackHeaders GatewayFilter Factory

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

application.yml.  +

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

+

In this example, after an execution exception occurs while running the HystrixCommand, the request will be forwarde 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:

  • executionExceptionTypeHeaderName ("Execution-Exception-Type")
  • executionExceptionMessageHeaderName ("Execution-Exception-Message")
  • rootCauseExceptionTypeHeaderName ("Root-Cause-Exception-Type")
  • rootCauseExceptionMessageHeaderName ("Root-Cause-Exception-Message")

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

5.6 PrefixPath GatewayFilter Factory

The PrefixPath GatewayFilter Factory takes a single prefix parameter.

application.yml. 

spring:
   cloud:
     gateway:
@@ -180,7 +230,7 @@ The Hystrix GatewayFilter allows you to introduce circuit breakers to your gatew
         uri: http://example.org
         filters:
         - PrefixPath=/mypath

-

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

5.6 PreserveHostHeader GatewayFilter Factory

The PreserveHostHeader GatewayFilter Factory has not 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.

application.yml.  +

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

5.7 PreserveHostHeader GatewayFilter Factory

The PreserveHostHeader GatewayFilter Factory has not 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.

application.yml. 

spring:
   cloud:
     gateway:
@@ -189,14 +239,14 @@ The Hystrix GatewayFilter allows you to introduce circuit breakers to your gatew
         uri: http://example.org
         filters:
         - PreserveHostHeader

-

5.7 RequestRateLimiter GatewayFilter Factory

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

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

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.java.  +

5.8 RequestRateLimiter GatewayFilter Factory

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

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

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.java. 

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

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

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

[Note]Note

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

application.properties. 

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

-

5.7.1 Redis RateLimiter

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.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.

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

application.yml.  +

5.8.1 Redis RateLimiter

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.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.

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

application.yml. 

spring:
   cloud:
     gateway:
@@ -225,7 +275,7 @@ KeyResolver userKeyResolver() {
           args:
             rate-limiter: "#{@myRateLimiter}"
             key-resolver: "#{@userKeyResolver}"

-

5.8 RedirectTo GatewayFilter Factory

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

application.yml.  +

5.9 RedirectTo GatewayFilter Factory

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

application.yml. 

spring:
   cloud:
     gateway:
@@ -234,7 +284,7 @@ KeyResolver userKeyResolver() {
         uri: http://example.org
         filters:
         - RedirectTo=302, http://acme.org

-

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

5.9 RemoveNonProxyHeaders GatewayFilter Factory

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

The default removed headers are:

  • Connection
  • Keep-Alive
  • Proxy-Authenticate
  • Proxy-Authorization
  • TE
  • Trailer
  • Transfer-Encoding
  • Upgrade

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

5.10 RemoveRequestHeader GatewayFilter Factory

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

application.yml.  +

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

5.10 RemoveNonProxyHeaders GatewayFilter Factory

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

The default removed headers are:

  • Connection
  • Keep-Alive
  • Proxy-Authenticate
  • Proxy-Authorization
  • TE
  • Trailer
  • Transfer-Encoding
  • Upgrade

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

5.11 RemoveRequestHeader GatewayFilter Factory

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

application.yml. 

spring:
   cloud:
     gateway:
@@ -243,7 +293,7 @@ KeyResolver userKeyResolver() {
         uri: http://example.org
         filters:
         - RemoveRequestHeader=X-Request-Foo

-

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

5.11 RemoveResponseHeader GatewayFilter Factory

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

application.yml.  +

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

5.12 RemoveResponseHeader GatewayFilter Factory

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

application.yml. 

spring:
   cloud:
     gateway:
@@ -252,7 +302,7 @@ KeyResolver userKeyResolver() {
         uri: http://example.org
         filters:
         - RemoveResponseHeader=X-Response-Foo

-

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

5.12 RewritePath GatewayFilter Factory

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

application.yml.  +

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

5.13 RewritePath GatewayFilter Factory

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

application.yml. 

spring:
   cloud:
     gateway:
@@ -263,7 +313,7 @@ KeyResolver userKeyResolver() {
         - Path=/foo/**
         filters:
         - RewritePath=/foo/(?<segment>.*), /$\{segment}

-

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

5.13 SaveSession GatewayFilter Factory

The SaveSession GatewayFilter Factory forces a WebSession::save operation before forwarding the call downstream. This is of particular use when +

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

5.14 SaveSession GatewayFilter Factory

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

application.yml. 

spring:
   cloud:
@@ -275,7 +325,7 @@ using something like         - Path=/foo/**
         filters:
         - SaveSession

-

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

5.14 SecureHeaders GatewayFilter Factory

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

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

  • X-Xss-Protection:1; mode=block
  • Strict-Transport-Security:max-age=631138519
  • X-Frame-Options:DENY
  • X-Content-Type-Options:nosniff
  • Referrer-Policy:no-referrer
  • Content-Security-Policy:default-src 'self' https:; font-src 'self' https: data:; img-src 'self' https: data:; object-src 'none'; script-src https:; style-src 'self' https: 'unsafe-inline'
  • X-Download-Options:noopen
  • X-Permitted-Cross-Domain-Policies:none

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

Property to change:

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

5.15 SetPath GatewayFilter Factory

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

application.yml.  +

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.

5.15 SecureHeaders GatewayFilter Factory

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

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

  • X-Xss-Protection:1; mode=block
  • Strict-Transport-Security:max-age=631138519
  • X-Frame-Options:DENY
  • X-Content-Type-Options:nosniff
  • Referrer-Policy:no-referrer
  • Content-Security-Policy:default-src 'self' https:; font-src 'self' https: data:; img-src 'self' https: data:; object-src 'none'; script-src https:; style-src 'self' https: 'unsafe-inline'
  • X-Download-Options:noopen
  • X-Permitted-Cross-Domain-Policies:none

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

Property to change:

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

5.16 SetPath GatewayFilter Factory

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

application.yml. 

spring:
   cloud:
     gateway:
@@ -286,7 +336,7 @@ using something like         - Path=/foo/{segment}
         filters:
         - SetPath=/{segment}

-

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

5.16 SetResponseHeader GatewayFilter Factory

The SetResponseHeader GatewayFilter Factory takes name and value parameters.

application.yml.  +

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

5.17 SetStatus GatewayFilter Factory

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

application.yml.  +

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.

5.18 SetStatus GatewayFilter Factory

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

application.yml. 

spring:
   cloud:
     gateway:
@@ -308,7 +358,7 @@ using something like         uri: http://example.org
         filters:
         - SetStatus=401

-

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

5.18 StripPrefix GatewayFilter Factory

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

application.yml.  +

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

5.19 StripPrefix GatewayFilter Factory

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

application.yml. 

spring:
   cloud:
     gateway:
@@ -319,7 +369,7 @@ using something like         - Path=/name/**
         filters:
         - StripPrefix=2

-

When a request is made through the gateway to /name/bar/foo the request made to nameservice will look like http://nameservice/foo.

5.19 Retry GatewayFilter Factory

The Retry GatewayFilter Factory takes retries, statuses, methods, and series as parameters.

  • retries: the number of retries that should be attempted
  • statuses: the HTTP status codes that should be retried, represented using org.springframework.http.HttpStatus
  • methods: the HTTP methods that should be retried, represented using org.springframework.http.HttpMethod
  • series: the series of status codes to be retried, represented using org.springframework.http.HttpStatus.Series

application.yml.  +

When a request is made through the gateway to /name/bar/foo the request made to nameservice will look like http://nameservice/foo.

5.20 Retry GatewayFilter Factory

The Retry GatewayFilter Factory takes retries, statuses, methods, and series as parameters.

  • retries: the number of retries that should be attempted
  • statuses: the HTTP status codes that should be retried, represented using org.springframework.http.HttpStatus
  • methods: the HTTP methods that should be retried, represented using org.springframework.http.HttpMethod
  • series: the series of status codes to be retried, represented using org.springframework.http.HttpStatus.Series

application.yml. 

spring:
   cloud:
     gateway:
@@ -333,7 +383,7 @@ using something like           args:
             retries: 3
             statuses: BAD_GATEWAY

-

[Note]Note

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

5.20 RequestSize GatewayFilter Factory

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

application.yml.  +

[Note]Note

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

5.21 RequestSize GatewayFilter Factory

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

application.yml. 

spring:
   cloud:
     gateway:
diff --git a/spring-cloud-gateway.xml b/spring-cloud-gateway.xml
index cf1c5fde..29eb3845 100644
--- a/spring-cloud-gateway.xml
+++ b/spring-cloud-gateway.xml
@@ -371,7 +371,7 @@ If two hops of trusted infrastructure are required before Spring Cloud Gateway i
 
 This will add X-Response-Foo:Bar header to the downstream response’s headers for all matching requests.
 
-
+
Hystrix GatewayFilter Factory Hystrix is a library from Netflix that implements the circuit breaker pattern. The Hystrix GatewayFilter allows you to introduce circuit breakers to your gateway routes, protecting your services from cascading failures and allowing you to provide fallback responses in the event of downstream failures. @@ -412,6 +412,38 @@ The Hystrix GatewayFilter allows you to introduce circuit breakers to your gatew 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. +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: + +application.yml + +spring: + cloud: + gateway: + routes: + - id: ingredients + uri: lb://ingredients + predicates: + - Path=//ingredients/** + filters: + - name: Hystrix + args: + name: fetchIngredients + fallbackUri: forward:/fallback + - id: ingredients-fallback + uri: http://localhost:9994 + predicates: + - Path=/fallback + + +In this example, there is no fallback endpoint or handler in the gateway application, however, there is one in another +app, registered under http://localhost:9994. +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. +For the external controller/ handler scenario, headers can be added with exception details. You can find more information +on it in the FallbackHeaders GatewayFilter Factory section. Hystrix settings (such as timeouts) can be configured with global defaults or on a route by route basis using application properties as explained on the Hystrix wiki. To set a 5 second timeout for the example route above, the following configuration would be used: @@ -421,6 +453,57 @@ The Hystrix GatewayFilter allows you to introduce circuit breakers to your gatew
+
+FallbackHeaders GatewayFilter Factory +The FallbackHeaders factory allows you to add Hystrix execution exception details in headers of a request forwarded to +a fallbackUri in an external application, like in the following scenario: + +application.yml + +spring: + cloud: + gateway: + routes: + - id: ingredients + uri: lb://ingredients + predicates: + - Path=//ingredients/** + filters: + - name: Hystrix + args: + name: fetchIngredients + fallbackUri: forward:/fallback + - id: ingredients-fallback + uri: http://localhost:9994 + predicates: + - Path=/fallback + filters: + - name: FallbackHeaders + args: + executionExceptionTypeHeaderName: Test-Header + + +In this example, after an execution exception occurs while running the HystrixCommand, the request will be forwarde 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: + + +executionExceptionTypeHeaderName ("Execution-Exception-Type") + + +executionExceptionMessageHeaderName ("Execution-Exception-Message") + + +rootCauseExceptionTypeHeaderName ("Root-Cause-Exception-Type") + + +rootCauseExceptionMessageHeaderName ("Root-Cause-Exception-Message") + + +You can find more information on how Hystrix works with Gateway in the Hystrix GatewayFilter Factory section. +
PrefixPath GatewayFilter Factory The PrefixPath GatewayFilter Factory takes a single prefix parameter.