diff --git a/reference/html/index.html b/reference/html/index.html index 30f4b421..e4408ab0 100644 --- a/reference/html/index.html +++ b/reference/html/index.html @@ -96,113 +96,130 @@ $(addBlockSwitches);
Table of Contents
@@ -218,7 +235,7 @@ $(addBlockSwitches);
-

How to Include Spring Cloud Gateway

+

1. How to Include Spring Cloud Gateway

To include Spring Cloud Gateway in your project use the starter with group org.springframework.cloud @@ -261,7 +278,7 @@ Spring Cloud Gateway requires the Netty runtime provided by Spring Boot and Spri

-

Glossary

+

2. Glossary

    @@ -279,13 +296,8 @@ Spring Cloud Gateway requires the Netty runtime provided by Spring Boot and Spri
-

How It Works

+

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.

@@ -304,13 +316,13 @@ URIs defined in routes without a port will get a default port set to 80 and 443
-

Route Predicate Factories

+

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.

-

After Route Predicate Factory

+

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.

@@ -332,7 +344,7 @@ URIs defined in routes without a port will get a default port set to 80 and 443
-

Before Route Predicate Factory

+

4.2. Before Route Predicate Factory

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

@@ -354,7 +366,7 @@ URIs defined in routes without a port will get a default port set to 80 and 443
-

Between Route Predicate Factory

+

4.3. Between Route Predicate Factory

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

@@ -376,7 +388,7 @@ URIs defined in routes without a port will get a default port set to 80 and 443
- +

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.

@@ -398,7 +410,7 @@ URIs defined in routes without a port will get a default port set to 80 and 443
-

Header Route Predicate Factory

+

4.5. Header Route Predicate Factory

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

@@ -420,7 +432,7 @@ URIs defined in routes without a port will get a default port set to 80 and 443
-

Host Route Predicate Factory

+

4.6. Host Route Predicate Factory

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

@@ -448,7 +460,7 @@ URIs defined in routes without a port will get a default port set to 80 and 443
-

Method Route Predicate Factory

+

4.7. Method Route Predicate Factory

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

@@ -470,7 +482,7 @@ URIs defined in routes without a port will get a default port set to 80 and 443
-

Path Route Predicate Factory

+

4.8. Path Route Predicate Factory

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

@@ -505,7 +517,7 @@ String segment = uriVariables.get("segment");
-

Query Route Predicate Factory

+

4.9. Query Route Predicate Factory

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

@@ -543,7 +555,7 @@ String segment = uriVariables.get("segment");
-

RemoteAddr Route Predicate Factory

+

4.10. RemoteAddr Route Predicate Factory

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

@@ -565,7 +577,7 @@ String segment = uriVariables.get("segment");
-

Weight Route Predicate Factory

+

4.11. Weight Route Predicate Factory

The Weight Route Predicate Factory takes two argument group and weight. The weights are calculated per group.

@@ -587,10 +599,10 @@ String segment = uriVariables.get("segment");
-

This route would forward ~80% of traffic to https://weighthigh.org and ~20% of traffic to https://weighlow.org

+

This route would forward ~80% of traffic to weighthigh.org and ~20% of traffic to weighlow.org

-

Modifying the way remote addresses are resolved

+

4.11.1. Modifying the way remote addresses are resolved

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

@@ -683,7 +695,7 @@ If two hops of trusted infrastructure are required before Spring Cloud Gateway i
-

GatewayFilter Factories

+

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

@@ -692,7 +704,7 @@ If two hops of trusted infrastructure are required before Spring Cloud Gateway i

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

-

AddRequestHeader GatewayFilter Factory

+

5.1. AddRequestHeader GatewayFilter Factory

The AddRequestHeader GatewayFilter Factory takes a name and value parameter.

@@ -732,7 +744,7 @@ If two hops of trusted infrastructure are required before Spring Cloud Gateway i
-

AddRequestParameter GatewayFilter Factory

+

5.2. AddRequestParameter GatewayFilter Factory

The AddRequestParameter GatewayFilter Factory takes a name and value parameter.

@@ -772,7 +784,7 @@ If two hops of trusted infrastructure are required before Spring Cloud Gateway i
-

AddResponseHeader GatewayFilter Factory

+

5.3. AddResponseHeader GatewayFilter Factory

The AddResponseHeader GatewayFilter Factory takes a name and value parameter.

@@ -812,7 +824,7 @@ If two hops of trusted infrastructure are required before Spring Cloud Gateway i
-

DedupeResponseHeader GatewayFilter Factory

+

5.4. DedupeResponseHeader GatewayFilter Factory

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

@@ -837,7 +849,7 @@ If two hops of trusted infrastructure are required before Spring Cloud Gateway i
-

Hystrix GatewayFilter Factory

+

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

@@ -917,7 +929,7 @@ However, it is also possible to reroute the request to a controller or handler i

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.

+app, registered under localhost:9994.

In case of the request being forwarded to fallback, the Hystrix Gateway filter also provides the Throwable that has @@ -943,7 +955,7 @@ on it in the FallbackHeaders GatewayFilter Factory

-

FallbackHeaders GatewayFilter Factory

+

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

@@ -1004,7 +1016,7 @@ their default values:

-

MapRequestHeader GatewayFilter Factory

+

5.7. MapRequestHeader GatewayFilter Factory

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 then the filter has no impact. If the new named header already exists then it’s values will be augmented with the new values.

@@ -1026,7 +1038,7 @@ their default values:

-

PrefixPath GatewayFilter Factory

+

5.8. PrefixPath GatewayFilter Factory

The PrefixPath GatewayFilter Factory takes a single prefix parameter.

@@ -1048,7 +1060,7 @@ their default values:

-

PreserveHostHeader GatewayFilter Factory

+

5.9. PreserveHostHeader GatewayFilter Factory

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

@@ -1067,7 +1079,7 @@ their default values:

-

RequestRateLimiter GatewayFilter Factory

+

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

@@ -1081,7 +1093,7 @@ their default values:

KeyResolver.java
public interface KeyResolver {
-	Mono<String> resolve(ServerWebExchange exchange);
+    Mono<String> resolve(ServerWebExchange exchange);
 }
@@ -1114,7 +1126,7 @@ spring.cloud.gateway.routes[0].filters[0]=RequestRateLimiter=2, 2, #{@userkeyres
-

Redis RateLimiter

+

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

@@ -1180,7 +1192,7 @@ KeyResolver userKeyResolver() {
-

RedirectTo GatewayFilter Factory

+

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

@@ -1202,7 +1214,7 @@ KeyResolver userKeyResolver() {
-

RemoveHopByHopHeadersFilter GatewayFilter Factory

+

5.12. RemoveHopByHopHeadersFilter GatewayFilter Factory

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

@@ -1240,7 +1252,7 @@ KeyResolver userKeyResolver() {
-

RemoveRequestHeader GatewayFilter Factory

+

5.13. RemoveRequestHeader GatewayFilter Factory

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

@@ -1262,7 +1274,7 @@ KeyResolver userKeyResolver() {
-

RemoveResponseHeader GatewayFilter Factory

+

5.14. RemoveResponseHeader GatewayFilter Factory

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

@@ -1289,7 +1301,7 @@ and have it applied to all routes.

-

RemoveRequestParameter GatewayFilter Factory

+

5.15. RemoveRequestParameter GatewayFilter Factory

The RemoveRequestParameter GatewayFilter Factory takes a name parameter. It is the name of the query parameter to be removed.

@@ -1311,7 +1323,7 @@ and have it applied to all routes.

-

RewritePath GatewayFilter Factory

+

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

@@ -1335,7 +1347,7 @@ and have it applied to all routes.

-

RewriteLocationResponseHeader GatewayFilter Factory

+

5.17. RewriteLocationResponseHeader GatewayFilter Factory

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

@@ -1353,7 +1365,7 @@ and have it applied to all routes.

-

For example, for a request POST https://api.example.com/some/object/name, Location response header value https://object-service.prod.example.net/v2/some/object/id will be rewritten as https://api.example.com/some/object/id.

+

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.

@@ -1379,7 +1391,7 @@ and have it applied to all routes.

-

RewriteResponseHeader GatewayFilter Factory

+

5.18. RewriteResponseHeader GatewayFilter Factory

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.

@@ -1401,7 +1413,7 @@ and have it applied to all routes.

-

SaveSession GatewayFilter Factory

+

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

@@ -1426,7 +1438,7 @@ using something like Spring
-

SecureHeaders GatewayFilter Factory

+

5.20. SecureHeaders GatewayFilter Factory

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

@@ -1500,7 +1512,7 @@ using something like Spring
-

SetPath GatewayFilter Factory

+

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

@@ -1524,7 +1536,7 @@ using something like Spring
-

SetRequestHeader GatewayFilter Factory

+

5.22. SetRequestHeader GatewayFilter Factory

The SetRequestHeader GatewayFilter Factory takes name and value parameters.

@@ -1564,7 +1576,7 @@ using something like Spring
-

SetResponseHeader GatewayFilter Factory

+

5.23. SetResponseHeader GatewayFilter Factory

The SetResponseHeader GatewayFilter Factory takes name and value parameters.

@@ -1604,7 +1616,7 @@ using something like Spring
-

SetStatus GatewayFilter Factory

+

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

@@ -1643,7 +1655,7 @@ using something like Spring
-

StripPrefix GatewayFilter Factory

+

5.25. StripPrefix GatewayFilter Factory

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

@@ -1663,11 +1675,11 @@ using something like Spring
-

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

+

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

-

Retry GatewayFilter Factory

+

5.26. Retry GatewayFilter Factory

The Retry GatewayFilter Factory support following set of parameters:

@@ -1766,7 +1778,7 @@ When using the retry filter with a forward: prefixed URL, the targe
-

RequestSize GatewayFilter Factory

+

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

@@ -1807,7 +1819,7 @@ The default Request size will be set to 5 MB if not provided as filter argument
-

Modify Request Body GatewayFilter Factory

+

5.28. Modify Request Body GatewayFilter Factory

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

@@ -1859,7 +1871,7 @@ static class Hello {
-

Modify Response Body GatewayFilter Factory

+

5.29. Modify Response Body GatewayFilter Factory

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

@@ -1885,15 +1897,15 @@ public RouteLocator routes(RouteLocatorBuilder builder) { return builder.routes() .route("rewrite_response_upper", r -> r.host("*.rewriteresponseupper.org") .filters(f -> f.prefixPath("/httpbin") - .modifyResponseBody(String.class, String.class, - (exchange, s) -> Mono.just(s.toUpperCase()))).uri(uri) + .modifyResponseBody(String.class, String.class, + (exchange, s) -> Mono.just(s.toUpperCase()))).uri(uri) .build(); }
-

Default Filters

+

5.30. Default Filters

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

@@ -1913,13 +1925,13 @@ This property takes a list of filters

-

Global Filters

+

6. Global Filters

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

-

Combined Global Filter and GatewayFilter Ordering

+

6.1. Combined Global Filter and GatewayFilter Ordering

When a request comes in (and matches a Route) the Filtering Web Handler will add all instances of GlobalFilter and all route specific instances of GatewayFilter to a filter chain. This combined filter chain is sorted by the org.springframework.core.Ordered interface, which can be set by implementing the getOrder() method or by using the @Order annotation.

@@ -1965,13 +1977,13 @@ public GlobalFilter c() {
-

Forward Routing Filter

+

6.2. Forward Routing Filter

The ForwardRoutingFilter looks for a URI in the exchange attribute ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR. If the url has a forward scheme (ie forward:///localendpoint), it will use the Spring DispatcherHandler to handler the request. The path part of the request URL will be overridden with the path in the forward URL. The unmodified original url is appended to the list in the ServerWebExchangeUtils.GATEWAY_ORIGINAL_REQUEST_URL_ATTR attribute.

-

LoadBalancerClient Filter

+

6.3. LoadBalancerClient Filter

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

@@ -2034,7 +2046,7 @@ You can switch to using it by setting the value of the spring.cloud.loadba
-

ReactiveLoadBalancerClientFilter

+

6.4. ReactiveLoadBalancerClientFilter

The ReactiveLoadBalancerClientFilter looks for a URI in the exchange attribute ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR. If the url has a lb scheme (ie lb://myservice), @@ -2089,19 +2101,19 @@ route URL will override the ServiceInstance configuration.

-

Netty Routing Filter

+

6.5. Netty Routing Filter

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

-

Netty Write Response Filter

+

6.6. Netty Write Response Filter

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)

-

RouteToRequestUrl Filter

+

6.7. RouteToRequestUrl Filter

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

@@ -2110,7 +2122,7 @@ route URL will override the ServiceInstance configuration.
-

Websocket Routing Filter

+

6.8. Websocket Routing Filter

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

@@ -2150,7 +2162,7 @@ If you are using SockJS as a fallback ov
-

Gateway Metrics Filter

+

6.9. Gateway Metrics Filter

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

@@ -2193,7 +2205,7 @@ To enable the prometheus endpoint add micrometer-registry-prometheus as a projec
-

Marking An Exchange As Routed

+

6.10. Marking An Exchange As Routed

After the Gateway has routed a ServerWebExchange it will mark that exchange as "routed" by adding gatewayAlreadyRouted to the exchange attributes. Once a request has been marked as routed, other routing filters will not route the request again, @@ -2214,7 +2226,7 @@ or check if an exchange has already been routed.

-

TLS / SSL

+

7. TLS / SSL

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

@@ -2265,7 +2277,7 @@ or check if an exchange has already been routed.

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

-

TLS Handshake

+

7.1. TLS Handshake

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

@@ -2286,7 +2298,7 @@ or check if an exchange has already been routed.

-

Configuration

+

8. Configuration

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

@@ -2295,7 +2307,7 @@ or check if an exchange has already been routed.

RouteDefinitionLocator.java
public interface RouteDefinitionLocator {
-	Flux<RouteDefinition> getRouteDefinitions();
+    Flux<RouteDefinition> getRouteDefinitions();
 }
@@ -2330,7 +2342,7 @@ or check if an exchange has already been routed.

-

Route metadata configuration

+

9. Route metadata configuration

Additional parameters can be configured for each route using metadata:

@@ -2364,7 +2376,7 @@ route.getMetadata(someKey);
-

Fluent Java Routes API

+

9.1. Fluent Java Routes API

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

@@ -2404,7 +2416,7 @@ public RouteLocator customRouteLocator(RouteLocatorBuilder builder, ThrottleGate
-

DiscoveryClient Route Definition Locator

+

9.2. DiscoveryClient Route Definition Locator

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

@@ -2412,7 +2424,7 @@ public RouteLocator customRouteLocator(RouteLocatorBuilder builder, ThrottleGate

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

-

Configuring Predicates and Filters For DiscoveryClient Routes

+

9.2.1. Configuring Predicates and Filters For DiscoveryClient Routes

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

@@ -2450,7 +2462,7 @@ spring.cloud.gateway.discovery.locator.filters[1].args[replacement]: "'/${remain
-

Reactor Netty Access Logs

+

10. Reactor Netty Access Logs

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

@@ -2479,7 +2491,7 @@ spring.cloud.gateway.discovery.locator.filters[1].args[replacement]: "'/${remain
-

CORS Configuration

+

11. CORS Configuration

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

@@ -2507,7 +2519,7 @@ spring.cloud.gateway.discovery.locator.filters[1].args[replacement]: "'/${remain
-

Actuator API

+

12. Actuator API

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

@@ -2520,7 +2532,7 @@ management.endpoints.web.exposure.include=gateway
-

Verbose Actuator Format

+

12.1. Verbose Actuator Format

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.

@@ -2558,9 +2570,9 @@ management.endpoints.web.exposure.include=gateway
-

Retrieving route filters

+

12.2. Retrieving route filters

-

Global Filters

+

12.2.1. Global Filters

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

@@ -2579,11 +2591,11 @@ 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 details of the global filters in place. For each global filter is provided the string representation of the filter object (e.g., org.springframework.cloud.gateway.filter.LoadBalancerClientFilter@77856cc5) and the corresponding order in the filter chain.

-

Route Filters

+

12.2.2. Route Filters

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

@@ -2602,13 +2614,13 @@ management.endpoints.web.exposure.include=gateway
-

Refreshing the route cache

+

12.3. Refreshing the route cache

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

-

Retrieving the routes defined in the gateway

+

12.4. Retrieving the routes defined in the gateway

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

@@ -2675,7 +2687,7 @@ management.endpoints.web.exposure.include=gateway
-

Retrieving information about a particular route

+

12.5. Retrieving information about a particular route

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

@@ -2739,7 +2751,7 @@ management.endpoints.web.exposure.include=gateway
-

Creating and deleting a particular route

+

12.6. Creating and deleting a particular route

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

@@ -2748,7 +2760,7 @@ management.endpoints.web.exposure.include=gateway
-

Recap: list of all endpoints

+

12.7. Recap: list of all endpoints

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

@@ -2807,10 +2819,10 @@ management.endpoints.web.exposure.include=gateway
-

Troubleshooting

+

13. Troubleshooting

-

Log Levels

+

13.1. Log Levels

Below are some useful loggers that contain valuable trouble shooting infomration at the DEBUG and TRACE levels.

@@ -2838,7 +2850,7 @@ management.endpoints.web.exposure.include=gateway
-

Wiretap

+

13.2. Wiretap

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 @@ -2851,19 +2863,19 @@ respectively.

-

Developer Guide

+

14. Developer Guide

TODO: overview of writing custom integrations

-

Writing Custom Route Predicate Factories

+

14.1. Writing Custom Route Predicate Factories

TODO: document writing Custom Route Predicate Factories

-

Writing Custom GatewayFilter Factories

+

14.2. Writing Custom GatewayFilter Factories

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

@@ -2872,25 +2884,25 @@ respectively.

public class PreGatewayFilterFactory extends AbstractGatewayFilterFactory<PreGatewayFilterFactory.Config> {
 
-	public PreGatewayFilterFactory() {
-		super(Config.class);
-	}
+    public PreGatewayFilterFactory() {
+        super(Config.class);
+    }
 
-	@Override
-	public GatewayFilter apply(Config config) {
-		// grab configuration from Config object
-		return (exchange, chain) -> {
+    @Override
+    public GatewayFilter apply(Config config) {
+        // grab configuration from Config object
+        return (exchange, chain) -> {
             //If you want to build a "pre" filter you need to manipulate the
             //request before calling chain.filter
             ServerHttpRequest.Builder builder = exchange.getRequest().mutate();
             //use builder to manipulate the request
             return chain.filter(exchange.mutate().request(request).build());
-		};
-	}
+        };
+    }
 
-	public static class Config {
+    public static class Config {
         //Put the configuration properties for your filter here
-	}
+    }
 
 }
@@ -2900,31 +2912,31 @@ respectively.

public class PostGatewayFilterFactory extends AbstractGatewayFilterFactory<PostGatewayFilterFactory.Config> {
 
-	public PostGatewayFilterFactory() {
-		super(Config.class);
-	}
+    public PostGatewayFilterFactory() {
+        super(Config.class);
+    }
 
-	@Override
-	public GatewayFilter apply(Config config) {
-		// grab configuration from Config object
-		return (exchange, chain) -> {
-			return chain.filter(exchange).then(Mono.fromRunnable(() -> {
-				ServerHttpResponse response = exchange.getResponse();
-				//Manipulate the response in some way
-			}));
-		};
-	}
+    @Override
+    public GatewayFilter apply(Config config) {
+        // grab configuration from Config object
+        return (exchange, chain) -> {
+            return chain.filter(exchange).then(Mono.fromRunnable(() -> {
+                ServerHttpResponse response = exchange.getResponse();
+                //Manipulate the response in some way
+            }));
+        };
+    }
 
-	public static class Config {
+    public static class Config {
         //Put the configuration properties for your filter here
-	}
+    }
 
 }
-

Writing Custom Global Filters

+

14.3. Writing Custom Global Filters

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

@@ -2962,7 +2974,7 @@ public GlobalFilter customGlobalPostFilter() {
-

Writing Custom Route Locators and Writers

+

14.4. Writing Custom Route Locators and Writers

TODO: document writing Custom Route Locators and Writers

@@ -2970,7 +2982,7 @@ public GlobalFilter customGlobalPostFilter() {
-

Building a Simple Gateway Using Spring MVC or Webflux

+

15. Building a Simple Gateway Using Spring MVC or Webflux

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

@@ -2984,13 +2996,13 @@ public GlobalFilter customGlobalPostFilter() { @SpringBootApplication public class GatewaySampleApplication { - @Value("${remote.home}") - private URI home; + @Value("${remote.home}") + private URI home; - @GetMapping("/test") - public ResponseEntity<?> proxy(ProxyExchange<byte[]> proxy) throws Exception { - return proxy.uri(home.toString() + "/image/png").get(); - } + @GetMapping("/test") + public ResponseEntity<?> proxy(ProxyExchange<byte[]> proxy) throws Exception { + return proxy.uri(home.toString() + "/image/png").get(); + } }
@@ -3004,13 +3016,13 @@ public class GatewaySampleApplication { @SpringBootApplication public class GatewaySampleApplication { - @Value("${remote.home}") - private URI home; + @Value("${remote.home}") + private URI home; - @GetMapping("/test") - public Mono<ResponseEntity<?>> proxy(ProxyExchange<byte[]> proxy) throws Exception { - return proxy.uri(home.toString() + "/image/png").get(); - } + @GetMapping("/test") + public Mono<ResponseEntity<?>> proxy(ProxyExchange<byte[]> proxy) throws Exception { + return proxy.uri(home.toString() + "/image/png").get(); + } }
@@ -3042,10 +3054,10 @@ public ResponseEntity<?> proxyPath(ProxyExchange<byte[]> proxy) thro
-

Configuration properties

+

16. Configuration properties

-

To see the list of all Sleuth related configuration properties please check the Appendix page.

+

To see the list of all Spring Cloud Gateway related configuration properties please check the Appendix page.

diff --git a/reference/html/spring-cloud-gateway.html b/reference/html/spring-cloud-gateway.html index 30f4b421..e4408ab0 100644 --- a/reference/html/spring-cloud-gateway.html +++ b/reference/html/spring-cloud-gateway.html @@ -96,113 +96,130 @@ $(addBlockSwitches);
Table of Contents
@@ -218,7 +235,7 @@ $(addBlockSwitches);
-

How to Include Spring Cloud Gateway

+

1. How to Include Spring Cloud Gateway

To include Spring Cloud Gateway in your project use the starter with group org.springframework.cloud @@ -261,7 +278,7 @@ Spring Cloud Gateway requires the Netty runtime provided by Spring Boot and Spri

-

Glossary

+

2. Glossary

    @@ -279,13 +296,8 @@ Spring Cloud Gateway requires the Netty runtime provided by Spring Boot and Spri
-

How It Works

+

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.

@@ -304,13 +316,13 @@ URIs defined in routes without a port will get a default port set to 80 and 443
-

Route Predicate Factories

+

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.

-

After Route Predicate Factory

+

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.

@@ -332,7 +344,7 @@ URIs defined in routes without a port will get a default port set to 80 and 443
-

Before Route Predicate Factory

+

4.2. Before Route Predicate Factory

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

@@ -354,7 +366,7 @@ URIs defined in routes without a port will get a default port set to 80 and 443
-

Between Route Predicate Factory

+

4.3. Between Route Predicate Factory

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

@@ -376,7 +388,7 @@ URIs defined in routes without a port will get a default port set to 80 and 443
- +

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.

@@ -398,7 +410,7 @@ URIs defined in routes without a port will get a default port set to 80 and 443
-

Header Route Predicate Factory

+

4.5. Header Route Predicate Factory

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

@@ -420,7 +432,7 @@ URIs defined in routes without a port will get a default port set to 80 and 443
-

Host Route Predicate Factory

+

4.6. Host Route Predicate Factory

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

@@ -448,7 +460,7 @@ URIs defined in routes without a port will get a default port set to 80 and 443
-

Method Route Predicate Factory

+

4.7. Method Route Predicate Factory

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

@@ -470,7 +482,7 @@ URIs defined in routes without a port will get a default port set to 80 and 443
-

Path Route Predicate Factory

+

4.8. Path Route Predicate Factory

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

@@ -505,7 +517,7 @@ String segment = uriVariables.get("segment");
-

Query Route Predicate Factory

+

4.9. Query Route Predicate Factory

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

@@ -543,7 +555,7 @@ String segment = uriVariables.get("segment");
-

RemoteAddr Route Predicate Factory

+

4.10. RemoteAddr Route Predicate Factory

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

@@ -565,7 +577,7 @@ String segment = uriVariables.get("segment");
-

Weight Route Predicate Factory

+

4.11. Weight Route Predicate Factory

The Weight Route Predicate Factory takes two argument group and weight. The weights are calculated per group.

@@ -587,10 +599,10 @@ String segment = uriVariables.get("segment");
-

This route would forward ~80% of traffic to https://weighthigh.org and ~20% of traffic to https://weighlow.org

+

This route would forward ~80% of traffic to weighthigh.org and ~20% of traffic to weighlow.org

-

Modifying the way remote addresses are resolved

+

4.11.1. Modifying the way remote addresses are resolved

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

@@ -683,7 +695,7 @@ If two hops of trusted infrastructure are required before Spring Cloud Gateway i
-

GatewayFilter Factories

+

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

@@ -692,7 +704,7 @@ If two hops of trusted infrastructure are required before Spring Cloud Gateway i

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

-

AddRequestHeader GatewayFilter Factory

+

5.1. AddRequestHeader GatewayFilter Factory

The AddRequestHeader GatewayFilter Factory takes a name and value parameter.

@@ -732,7 +744,7 @@ If two hops of trusted infrastructure are required before Spring Cloud Gateway i
-

AddRequestParameter GatewayFilter Factory

+

5.2. AddRequestParameter GatewayFilter Factory

The AddRequestParameter GatewayFilter Factory takes a name and value parameter.

@@ -772,7 +784,7 @@ If two hops of trusted infrastructure are required before Spring Cloud Gateway i
-

AddResponseHeader GatewayFilter Factory

+

5.3. AddResponseHeader GatewayFilter Factory

The AddResponseHeader GatewayFilter Factory takes a name and value parameter.

@@ -812,7 +824,7 @@ If two hops of trusted infrastructure are required before Spring Cloud Gateway i
-

DedupeResponseHeader GatewayFilter Factory

+

5.4. DedupeResponseHeader GatewayFilter Factory

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

@@ -837,7 +849,7 @@ If two hops of trusted infrastructure are required before Spring Cloud Gateway i
-

Hystrix GatewayFilter Factory

+

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

@@ -917,7 +929,7 @@ However, it is also possible to reroute the request to a controller or handler i

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.

+app, registered under localhost:9994.

In case of the request being forwarded to fallback, the Hystrix Gateway filter also provides the Throwable that has @@ -943,7 +955,7 @@ on it in the FallbackHeaders GatewayFilter Factory

-

FallbackHeaders GatewayFilter Factory

+

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

@@ -1004,7 +1016,7 @@ their default values:

-

MapRequestHeader GatewayFilter Factory

+

5.7. MapRequestHeader GatewayFilter Factory

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 then the filter has no impact. If the new named header already exists then it’s values will be augmented with the new values.

@@ -1026,7 +1038,7 @@ their default values:

-

PrefixPath GatewayFilter Factory

+

5.8. PrefixPath GatewayFilter Factory

The PrefixPath GatewayFilter Factory takes a single prefix parameter.

@@ -1048,7 +1060,7 @@ their default values:

-

PreserveHostHeader GatewayFilter Factory

+

5.9. PreserveHostHeader GatewayFilter Factory

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

@@ -1067,7 +1079,7 @@ their default values:

-

RequestRateLimiter GatewayFilter Factory

+

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

@@ -1081,7 +1093,7 @@ their default values:

KeyResolver.java
public interface KeyResolver {
-	Mono<String> resolve(ServerWebExchange exchange);
+    Mono<String> resolve(ServerWebExchange exchange);
 }
@@ -1114,7 +1126,7 @@ spring.cloud.gateway.routes[0].filters[0]=RequestRateLimiter=2, 2, #{@userkeyres
-

Redis RateLimiter

+

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

@@ -1180,7 +1192,7 @@ KeyResolver userKeyResolver() {
-

RedirectTo GatewayFilter Factory

+

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

@@ -1202,7 +1214,7 @@ KeyResolver userKeyResolver() {
-

RemoveHopByHopHeadersFilter GatewayFilter Factory

+

5.12. RemoveHopByHopHeadersFilter GatewayFilter Factory

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

@@ -1240,7 +1252,7 @@ KeyResolver userKeyResolver() {
-

RemoveRequestHeader GatewayFilter Factory

+

5.13. RemoveRequestHeader GatewayFilter Factory

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

@@ -1262,7 +1274,7 @@ KeyResolver userKeyResolver() {
-

RemoveResponseHeader GatewayFilter Factory

+

5.14. RemoveResponseHeader GatewayFilter Factory

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

@@ -1289,7 +1301,7 @@ and have it applied to all routes.

-

RemoveRequestParameter GatewayFilter Factory

+

5.15. RemoveRequestParameter GatewayFilter Factory

The RemoveRequestParameter GatewayFilter Factory takes a name parameter. It is the name of the query parameter to be removed.

@@ -1311,7 +1323,7 @@ and have it applied to all routes.

-

RewritePath GatewayFilter Factory

+

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

@@ -1335,7 +1347,7 @@ and have it applied to all routes.

-

RewriteLocationResponseHeader GatewayFilter Factory

+

5.17. RewriteLocationResponseHeader GatewayFilter Factory

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

@@ -1353,7 +1365,7 @@ and have it applied to all routes.

-

For example, for a request POST https://api.example.com/some/object/name, Location response header value https://object-service.prod.example.net/v2/some/object/id will be rewritten as https://api.example.com/some/object/id.

+

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.

@@ -1379,7 +1391,7 @@ and have it applied to all routes.

-

RewriteResponseHeader GatewayFilter Factory

+

5.18. RewriteResponseHeader GatewayFilter Factory

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.

@@ -1401,7 +1413,7 @@ and have it applied to all routes.

-

SaveSession GatewayFilter Factory

+

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

@@ -1426,7 +1438,7 @@ using something like Spring
-

SecureHeaders GatewayFilter Factory

+

5.20. SecureHeaders GatewayFilter Factory

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

@@ -1500,7 +1512,7 @@ using something like Spring
-

SetPath GatewayFilter Factory

+

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

@@ -1524,7 +1536,7 @@ using something like Spring
-

SetRequestHeader GatewayFilter Factory

+

5.22. SetRequestHeader GatewayFilter Factory

The SetRequestHeader GatewayFilter Factory takes name and value parameters.

@@ -1564,7 +1576,7 @@ using something like Spring
-

SetResponseHeader GatewayFilter Factory

+

5.23. SetResponseHeader GatewayFilter Factory

The SetResponseHeader GatewayFilter Factory takes name and value parameters.

@@ -1604,7 +1616,7 @@ using something like Spring
-

SetStatus GatewayFilter Factory

+

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

@@ -1643,7 +1655,7 @@ using something like Spring
-

StripPrefix GatewayFilter Factory

+

5.25. StripPrefix GatewayFilter Factory

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

@@ -1663,11 +1675,11 @@ using something like Spring
-

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

+

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

-

Retry GatewayFilter Factory

+

5.26. Retry GatewayFilter Factory

The Retry GatewayFilter Factory support following set of parameters:

@@ -1766,7 +1778,7 @@ When using the retry filter with a forward: prefixed URL, the targe
-

RequestSize GatewayFilter Factory

+

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

@@ -1807,7 +1819,7 @@ The default Request size will be set to 5 MB if not provided as filter argument
-

Modify Request Body GatewayFilter Factory

+

5.28. Modify Request Body GatewayFilter Factory

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

@@ -1859,7 +1871,7 @@ static class Hello {
-

Modify Response Body GatewayFilter Factory

+

5.29. Modify Response Body GatewayFilter Factory

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

@@ -1885,15 +1897,15 @@ public RouteLocator routes(RouteLocatorBuilder builder) { return builder.routes() .route("rewrite_response_upper", r -> r.host("*.rewriteresponseupper.org") .filters(f -> f.prefixPath("/httpbin") - .modifyResponseBody(String.class, String.class, - (exchange, s) -> Mono.just(s.toUpperCase()))).uri(uri) + .modifyResponseBody(String.class, String.class, + (exchange, s) -> Mono.just(s.toUpperCase()))).uri(uri) .build(); }
-

Default Filters

+

5.30. Default Filters

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

@@ -1913,13 +1925,13 @@ This property takes a list of filters

-

Global Filters

+

6. Global Filters

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

-

Combined Global Filter and GatewayFilter Ordering

+

6.1. Combined Global Filter and GatewayFilter Ordering

When a request comes in (and matches a Route) the Filtering Web Handler will add all instances of GlobalFilter and all route specific instances of GatewayFilter to a filter chain. This combined filter chain is sorted by the org.springframework.core.Ordered interface, which can be set by implementing the getOrder() method or by using the @Order annotation.

@@ -1965,13 +1977,13 @@ public GlobalFilter c() {
-

Forward Routing Filter

+

6.2. Forward Routing Filter

The ForwardRoutingFilter looks for a URI in the exchange attribute ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR. If the url has a forward scheme (ie forward:///localendpoint), it will use the Spring DispatcherHandler to handler the request. The path part of the request URL will be overridden with the path in the forward URL. The unmodified original url is appended to the list in the ServerWebExchangeUtils.GATEWAY_ORIGINAL_REQUEST_URL_ATTR attribute.

-

LoadBalancerClient Filter

+

6.3. LoadBalancerClient Filter

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

@@ -2034,7 +2046,7 @@ You can switch to using it by setting the value of the spring.cloud.loadba
-

ReactiveLoadBalancerClientFilter

+

6.4. ReactiveLoadBalancerClientFilter

The ReactiveLoadBalancerClientFilter looks for a URI in the exchange attribute ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR. If the url has a lb scheme (ie lb://myservice), @@ -2089,19 +2101,19 @@ route URL will override the ServiceInstance configuration.

-

Netty Routing Filter

+

6.5. Netty Routing Filter

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

-

Netty Write Response Filter

+

6.6. Netty Write Response Filter

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)

-

RouteToRequestUrl Filter

+

6.7. RouteToRequestUrl Filter

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

@@ -2110,7 +2122,7 @@ route URL will override the ServiceInstance configuration.
-

Websocket Routing Filter

+

6.8. Websocket Routing Filter

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

@@ -2150,7 +2162,7 @@ If you are using SockJS as a fallback ov
-

Gateway Metrics Filter

+

6.9. Gateway Metrics Filter

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

@@ -2193,7 +2205,7 @@ To enable the prometheus endpoint add micrometer-registry-prometheus as a projec
-

Marking An Exchange As Routed

+

6.10. Marking An Exchange As Routed

After the Gateway has routed a ServerWebExchange it will mark that exchange as "routed" by adding gatewayAlreadyRouted to the exchange attributes. Once a request has been marked as routed, other routing filters will not route the request again, @@ -2214,7 +2226,7 @@ or check if an exchange has already been routed.

-

TLS / SSL

+

7. TLS / SSL

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

@@ -2265,7 +2277,7 @@ or check if an exchange has already been routed.

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

-

TLS Handshake

+

7.1. TLS Handshake

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

@@ -2286,7 +2298,7 @@ or check if an exchange has already been routed.

-

Configuration

+

8. Configuration

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

@@ -2295,7 +2307,7 @@ or check if an exchange has already been routed.

RouteDefinitionLocator.java
public interface RouteDefinitionLocator {
-	Flux<RouteDefinition> getRouteDefinitions();
+    Flux<RouteDefinition> getRouteDefinitions();
 }
@@ -2330,7 +2342,7 @@ or check if an exchange has already been routed.

-

Route metadata configuration

+

9. Route metadata configuration

Additional parameters can be configured for each route using metadata:

@@ -2364,7 +2376,7 @@ route.getMetadata(someKey);
-

Fluent Java Routes API

+

9.1. Fluent Java Routes API

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

@@ -2404,7 +2416,7 @@ public RouteLocator customRouteLocator(RouteLocatorBuilder builder, ThrottleGate
-

DiscoveryClient Route Definition Locator

+

9.2. DiscoveryClient Route Definition Locator

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

@@ -2412,7 +2424,7 @@ public RouteLocator customRouteLocator(RouteLocatorBuilder builder, ThrottleGate

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

-

Configuring Predicates and Filters For DiscoveryClient Routes

+

9.2.1. Configuring Predicates and Filters For DiscoveryClient Routes

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

@@ -2450,7 +2462,7 @@ spring.cloud.gateway.discovery.locator.filters[1].args[replacement]: "'/${remain
-

Reactor Netty Access Logs

+

10. Reactor Netty Access Logs

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

@@ -2479,7 +2491,7 @@ spring.cloud.gateway.discovery.locator.filters[1].args[replacement]: "'/${remain
-

CORS Configuration

+

11. CORS Configuration

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

@@ -2507,7 +2519,7 @@ spring.cloud.gateway.discovery.locator.filters[1].args[replacement]: "'/${remain
-

Actuator API

+

12. Actuator API

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

@@ -2520,7 +2532,7 @@ management.endpoints.web.exposure.include=gateway
-

Verbose Actuator Format

+

12.1. Verbose Actuator Format

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.

@@ -2558,9 +2570,9 @@ management.endpoints.web.exposure.include=gateway
-

Retrieving route filters

+

12.2. Retrieving route filters

-

Global Filters

+

12.2.1. Global Filters

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

@@ -2579,11 +2591,11 @@ 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 details of the global filters in place. For each global filter is provided the string representation of the filter object (e.g., org.springframework.cloud.gateway.filter.LoadBalancerClientFilter@77856cc5) and the corresponding order in the filter chain.

-

Route Filters

+

12.2.2. Route Filters

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

@@ -2602,13 +2614,13 @@ management.endpoints.web.exposure.include=gateway
-

Refreshing the route cache

+

12.3. Refreshing the route cache

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

-

Retrieving the routes defined in the gateway

+

12.4. Retrieving the routes defined in the gateway

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

@@ -2675,7 +2687,7 @@ management.endpoints.web.exposure.include=gateway
-

Retrieving information about a particular route

+

12.5. Retrieving information about a particular route

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

@@ -2739,7 +2751,7 @@ management.endpoints.web.exposure.include=gateway
-

Creating and deleting a particular route

+

12.6. Creating and deleting a particular route

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

@@ -2748,7 +2760,7 @@ management.endpoints.web.exposure.include=gateway
-

Recap: list of all endpoints

+

12.7. Recap: list of all endpoints

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

@@ -2807,10 +2819,10 @@ management.endpoints.web.exposure.include=gateway
-

Troubleshooting

+

13. Troubleshooting

-

Log Levels

+

13.1. Log Levels

Below are some useful loggers that contain valuable trouble shooting infomration at the DEBUG and TRACE levels.

@@ -2838,7 +2850,7 @@ management.endpoints.web.exposure.include=gateway
-

Wiretap

+

13.2. Wiretap

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 @@ -2851,19 +2863,19 @@ respectively.

-

Developer Guide

+

14. Developer Guide

TODO: overview of writing custom integrations

-

Writing Custom Route Predicate Factories

+

14.1. Writing Custom Route Predicate Factories

TODO: document writing Custom Route Predicate Factories

-

Writing Custom GatewayFilter Factories

+

14.2. Writing Custom GatewayFilter Factories

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

@@ -2872,25 +2884,25 @@ respectively.

public class PreGatewayFilterFactory extends AbstractGatewayFilterFactory<PreGatewayFilterFactory.Config> {
 
-	public PreGatewayFilterFactory() {
-		super(Config.class);
-	}
+    public PreGatewayFilterFactory() {
+        super(Config.class);
+    }
 
-	@Override
-	public GatewayFilter apply(Config config) {
-		// grab configuration from Config object
-		return (exchange, chain) -> {
+    @Override
+    public GatewayFilter apply(Config config) {
+        // grab configuration from Config object
+        return (exchange, chain) -> {
             //If you want to build a "pre" filter you need to manipulate the
             //request before calling chain.filter
             ServerHttpRequest.Builder builder = exchange.getRequest().mutate();
             //use builder to manipulate the request
             return chain.filter(exchange.mutate().request(request).build());
-		};
-	}
+        };
+    }
 
-	public static class Config {
+    public static class Config {
         //Put the configuration properties for your filter here
-	}
+    }
 
 }
@@ -2900,31 +2912,31 @@ respectively.

public class PostGatewayFilterFactory extends AbstractGatewayFilterFactory<PostGatewayFilterFactory.Config> {
 
-	public PostGatewayFilterFactory() {
-		super(Config.class);
-	}
+    public PostGatewayFilterFactory() {
+        super(Config.class);
+    }
 
-	@Override
-	public GatewayFilter apply(Config config) {
-		// grab configuration from Config object
-		return (exchange, chain) -> {
-			return chain.filter(exchange).then(Mono.fromRunnable(() -> {
-				ServerHttpResponse response = exchange.getResponse();
-				//Manipulate the response in some way
-			}));
-		};
-	}
+    @Override
+    public GatewayFilter apply(Config config) {
+        // grab configuration from Config object
+        return (exchange, chain) -> {
+            return chain.filter(exchange).then(Mono.fromRunnable(() -> {
+                ServerHttpResponse response = exchange.getResponse();
+                //Manipulate the response in some way
+            }));
+        };
+    }
 
-	public static class Config {
+    public static class Config {
         //Put the configuration properties for your filter here
-	}
+    }
 
 }
-

Writing Custom Global Filters

+

14.3. Writing Custom Global Filters

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

@@ -2962,7 +2974,7 @@ public GlobalFilter customGlobalPostFilter() {
-

Writing Custom Route Locators and Writers

+

14.4. Writing Custom Route Locators and Writers

TODO: document writing Custom Route Locators and Writers

@@ -2970,7 +2982,7 @@ public GlobalFilter customGlobalPostFilter() {
-

Building a Simple Gateway Using Spring MVC or Webflux

+

15. Building a Simple Gateway Using Spring MVC or Webflux

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

@@ -2984,13 +2996,13 @@ public GlobalFilter customGlobalPostFilter() { @SpringBootApplication public class GatewaySampleApplication { - @Value("${remote.home}") - private URI home; + @Value("${remote.home}") + private URI home; - @GetMapping("/test") - public ResponseEntity<?> proxy(ProxyExchange<byte[]> proxy) throws Exception { - return proxy.uri(home.toString() + "/image/png").get(); - } + @GetMapping("/test") + public ResponseEntity<?> proxy(ProxyExchange<byte[]> proxy) throws Exception { + return proxy.uri(home.toString() + "/image/png").get(); + } }
@@ -3004,13 +3016,13 @@ public class GatewaySampleApplication { @SpringBootApplication public class GatewaySampleApplication { - @Value("${remote.home}") - private URI home; + @Value("${remote.home}") + private URI home; - @GetMapping("/test") - public Mono<ResponseEntity<?>> proxy(ProxyExchange<byte[]> proxy) throws Exception { - return proxy.uri(home.toString() + "/image/png").get(); - } + @GetMapping("/test") + public Mono<ResponseEntity<?>> proxy(ProxyExchange<byte[]> proxy) throws Exception { + return proxy.uri(home.toString() + "/image/png").get(); + } }
@@ -3042,10 +3054,10 @@ public ResponseEntity<?> proxyPath(ProxyExchange<byte[]> proxy) thro
-

Configuration properties

+

16. Configuration properties

-

To see the list of all Sleuth related configuration properties please check the Appendix page.

+

To see the list of all Spring Cloud Gateway related configuration properties please check the Appendix page.