-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);
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
-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.
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.
The After Route Predicate Factory takes one parameter, a datetime. This predicate matches requests that happen after the current datetime.
The Before Route Predicate Factory takes one parameter, a datetime. This predicate matches requests that happen before the current datetime.
The Between Route Predicate Factory takes two parameters, datetime1 and datetime2. This predicate matches requests that happen after datetime1 and before datetime2. The datetime2 parameter must be after datetime1.
The Cookie Route Predicate Factory takes two parameters, the cookie name and a regular expression. This predicate matches cookies that have the given name and the value matches the regular expression.
The Header Route Predicate Factory takes two parameters, the header name and a regular expression. This predicate matches with a header that has the given name and the value matches the regular expression.
The Host Route Predicate Factory takes one parameter: a list of host name patterns. The pattern is an Ant style pattern with . as the separator. This predicates matches the Host header that matches the pattern.
The Method Route Predicate Factory takes one parameter: the HTTP method to match.
The Path Route Predicate Factory takes two parameters: a list of Spring PathMatcher patterns and an optional flag to matchOptionalTrailingSeparator.
The Query Route Predicate Factory takes two parameters: a required param and an optional regexp.
The RemoteAddr Route Predicate Factory takes a list (min size 1) of CIDR-notation (IPv4 or IPv6) strings, e.g. 192.168.0.1/16 (where 192.168.0.1 is an IP address and 16 is a subnet mask).
The Weight Route Predicate Factory takes two argument group and weight. The weights are calculated per group.
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
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 iRoute 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 iNOTE For more detailed examples on how to use any of the following filters, take a look at the unit tests.
The AddRequestHeader GatewayFilter Factory takes a name and value parameter.
The AddRequestParameter GatewayFilter Factory takes a name and value parameter.
The AddResponseHeader GatewayFilter Factory takes a name and value parameter.
The DedupeResponseHeader GatewayFilter Factory takes a name parameter and an optional strategy parameter. name can contain a list of header names, space separated.
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 iIn 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.
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
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:
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.
The PrefixPath GatewayFilter Factory takes a single prefix parameter.
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.
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.
public interface KeyResolver {
- Mono<String> resolve(ServerWebExchange exchange);
+ Mono<String> resolve(ServerWebExchange exchange);
}
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 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.
The RemoveHopByHopHeadersFilter GatewayFilter Factory removes headers from forwarded requests. The default list of headers that is removed comes from the IETF.
The RemoveRequestHeader GatewayFilter Factory takes a name parameter. It is the name of the header to be removed.
The RemoveResponseHeader GatewayFilter Factory takes a name parameter. It is the name of the header to be removed.
The RemoveRequestParameter GatewayFilter Factory takes a name parameter. It is the name of the query parameter to be removed.
The RewritePath GatewayFilter Factory takes a path regexp parameter and a replacement parameter. This uses Java regular expressions for a flexible way to rewrite the request path.
The 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.
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.
The RewriteResponseHeader GatewayFilter Factory takes name, regexp, and replacement parameters. It uses Java regular expressions for a flexible way to rewrite the response header value.
The SaveSession GatewayFilter Factory forces a WebSession::save operation before forwarding the call downstream. This is of particular use when
using something like Spring Session with a lazy data store and need to ensure the session state has been saved before making the forwarded call.
The SecureHeaders GatewayFilter Factory adds a number of headers to the response at the recommendation from this blog post.
The SetPath GatewayFilter Factory takes a path template parameter. It offers a simple way to manipulate the request path by allowing templated segments of the path. This uses the uri templates from Spring Framework. Multiple matching segments are allowed.
The SetRequestHeader GatewayFilter Factory takes name and value parameters.
The SetResponseHeader GatewayFilter Factory takes name and value parameters.
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.
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.
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.
The Retry GatewayFilter Factory support following set of parameters:
forward: prefixed URL, the targe
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.
This filter is considered BETA and the API may change in the future
This filter is considered BETA and the API may change in the future
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
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).
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.
The ForwardRoutingFilter looks for a URI in the exchange attribute ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR. If the url has a forward scheme (ie forward:///localendpoint), it will use the Spring DispatcherHandler to handler the request. The path part of the request URL will be overridden with the path in the forward URL. The unmodified original url is appended to the list in the ServerWebExchangeUtils.GATEWAY_ORIGINAL_REQUEST_URL_ATTR attribute.
The 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.
spring.cloud.loadba
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.
The Netty Routing Filter runs if the url located in the ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR exchange attribute has a http or https scheme. It uses the Netty HttpClient to make the downstream proxy request. The response is put in the ServerWebExchangeUtils.CLIENT_RESPONSE_ATTR exchange attribute for use in a later filter. (There is an experimental WebClientHttpRoutingFilter that performs the same function, but does not require netty)
The NettyWriteResponseFilter runs if there is a Netty HttpClientResponse in the ServerWebExchangeUtils.CLIENT_RESPONSE_ATTR exchange attribute. It is run after all other filters have completed and writes the proxy response back to the gateway client response. (There is an experimental WebClientWriteResponseFilter that performs the same function, but does not require netty)
The 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`.
ServiceInstance configuration.
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.
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:
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.
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).
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):
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.public interface RouteDefinitionLocator {
- Flux<RouteDefinition> getRouteDefinitions();
+ Flux<RouteDefinition> getRouteDefinitions();
}
Additional parameters can be configured for each route using metadata:
@@ -2364,7 +2376,7 @@ route.getMetadata(someKey);To allow for simple configuration in Java, there is a fluent API defined in the RouteLocatorBuilder bean.
The Gateway can be configured to create routes based on services registered with a DiscoveryClient compatible service registry.
To enable this, set spring.cloud.gateway.discovery.locator.enabled=true and make sure a DiscoveryClient implementation is on the classpath and enabled (such as Netflix Eureka, Consul or Zookeeper).
By default the Gateway defines a single predicate and filter for routes created via a DiscoveryClient.
To enable Reactor Netty access logs, set -Dreactor.netty.http.server.accessLogEnabled=true. (It must be a Java System Property, not a Spring Boot property).
The gateway can be configured to control CORS behavior. The "global" CORS configuration is a map of URL patterns to Spring Framework CorsConfiguration.
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.
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.
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:
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.
To retrieve the GatewayFilter factories applied to routes, make a GET request to /actuator/gateway/routefilters. The resulting response is similar to the following:
To clear the routes cache, make a POST request to /actuator/gateway/refresh. The request returns a 200 without response body.
To retrieve the routes defined in the gateway, make a GET request to /actuator/gateway/routes. The resulting response is similar to the following:
To retrieve information about a single route, make a GET request to /actuator/gateway/routes/{id} (e.g., /actuator/gateway/routes/first_route). The resulting response is similar to the following:
To 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).
The table below summarises the Spring Cloud Gateway actuator endpoints. Note that each endpoint has /actuator/gateway as the base-path.
Below are some useful loggers that contain valuable trouble shooting infomration at the DEBUG and TRACE levels.
The Reactor Netty HttpClient and HttpServer can have wiretap enabled. When combined
with setting the reactor.netty log level to DEBUG or TRACE will enable logging of
@@ -2851,19 +2863,19 @@ respectively.
TODO: overview of writing custom integrations
TODO: document writing Custom Route Predicate Factories
In order to write a GatewayFilter you will need to implement GatewayFilterFactory. There is an abstract class called AbstractGatewayFilterFactory which you can extend.
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
- }
+ }
}
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
- }
+ }
}
In order to write a custom global filter, you will need to implement GlobalFilter interface. This will apply the filter to all requests.
TODO: document writing Custom Route Locators and Writers
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).
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.
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
-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.
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.
The After Route Predicate Factory takes one parameter, a datetime. This predicate matches requests that happen after the current datetime.
The Before Route Predicate Factory takes one parameter, a datetime. This predicate matches requests that happen before the current datetime.
The Between Route Predicate Factory takes two parameters, datetime1 and datetime2. This predicate matches requests that happen after datetime1 and before datetime2. The datetime2 parameter must be after datetime1.
The Cookie Route Predicate Factory takes two parameters, the cookie name and a regular expression. This predicate matches cookies that have the given name and the value matches the regular expression.
The Header Route Predicate Factory takes two parameters, the header name and a regular expression. This predicate matches with a header that has the given name and the value matches the regular expression.
The Host Route Predicate Factory takes one parameter: a list of host name patterns. The pattern is an Ant style pattern with . as the separator. This predicates matches the Host header that matches the pattern.
The Method Route Predicate Factory takes one parameter: the HTTP method to match.
The Path Route Predicate Factory takes two parameters: a list of Spring PathMatcher patterns and an optional flag to matchOptionalTrailingSeparator.
The Query Route Predicate Factory takes two parameters: a required param and an optional regexp.
The RemoteAddr Route Predicate Factory takes a list (min size 1) of CIDR-notation (IPv4 or IPv6) strings, e.g. 192.168.0.1/16 (where 192.168.0.1 is an IP address and 16 is a subnet mask).
The Weight Route Predicate Factory takes two argument group and weight. The weights are calculated per group.
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
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 iRoute 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 iNOTE For more detailed examples on how to use any of the following filters, take a look at the unit tests.
The AddRequestHeader GatewayFilter Factory takes a name and value parameter.
The AddRequestParameter GatewayFilter Factory takes a name and value parameter.
The AddResponseHeader GatewayFilter Factory takes a name and value parameter.
The DedupeResponseHeader GatewayFilter Factory takes a name parameter and an optional strategy parameter. name can contain a list of header names, space separated.
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 iIn 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.
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
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:
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.
The PrefixPath GatewayFilter Factory takes a single prefix parameter.
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.
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.
public interface KeyResolver {
- Mono<String> resolve(ServerWebExchange exchange);
+ Mono<String> resolve(ServerWebExchange exchange);
}
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 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.
The RemoveHopByHopHeadersFilter GatewayFilter Factory removes headers from forwarded requests. The default list of headers that is removed comes from the IETF.
The RemoveRequestHeader GatewayFilter Factory takes a name parameter. It is the name of the header to be removed.
The RemoveResponseHeader GatewayFilter Factory takes a name parameter. It is the name of the header to be removed.
The RemoveRequestParameter GatewayFilter Factory takes a name parameter. It is the name of the query parameter to be removed.
The RewritePath GatewayFilter Factory takes a path regexp parameter and a replacement parameter. This uses Java regular expressions for a flexible way to rewrite the request path.
The 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.
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.
The RewriteResponseHeader GatewayFilter Factory takes name, regexp, and replacement parameters. It uses Java regular expressions for a flexible way to rewrite the response header value.
The SaveSession GatewayFilter Factory forces a WebSession::save operation before forwarding the call downstream. This is of particular use when
using something like Spring Session with a lazy data store and need to ensure the session state has been saved before making the forwarded call.
The SecureHeaders GatewayFilter Factory adds a number of headers to the response at the recommendation from this blog post.
The SetPath GatewayFilter Factory takes a path template parameter. It offers a simple way to manipulate the request path by allowing templated segments of the path. This uses the uri templates from Spring Framework. Multiple matching segments are allowed.
The SetRequestHeader GatewayFilter Factory takes name and value parameters.
The SetResponseHeader GatewayFilter Factory takes name and value parameters.
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.
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.
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.
The Retry GatewayFilter Factory support following set of parameters:
forward: prefixed URL, the targe
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.
This filter is considered BETA and the API may change in the future
This filter is considered BETA and the API may change in the future
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
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).
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.
The ForwardRoutingFilter looks for a URI in the exchange attribute ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR. If the url has a forward scheme (ie forward:///localendpoint), it will use the Spring DispatcherHandler to handler the request. The path part of the request URL will be overridden with the path in the forward URL. The unmodified original url is appended to the list in the ServerWebExchangeUtils.GATEWAY_ORIGINAL_REQUEST_URL_ATTR attribute.
The 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.
spring.cloud.loadba
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.
The Netty Routing Filter runs if the url located in the ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR exchange attribute has a http or https scheme. It uses the Netty HttpClient to make the downstream proxy request. The response is put in the ServerWebExchangeUtils.CLIENT_RESPONSE_ATTR exchange attribute for use in a later filter. (There is an experimental WebClientHttpRoutingFilter that performs the same function, but does not require netty)
The NettyWriteResponseFilter runs if there is a Netty HttpClientResponse in the ServerWebExchangeUtils.CLIENT_RESPONSE_ATTR exchange attribute. It is run after all other filters have completed and writes the proxy response back to the gateway client response. (There is an experimental WebClientWriteResponseFilter that performs the same function, but does not require netty)
The 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`.
ServiceInstance configuration.
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.
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:
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.
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).
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):
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.public interface RouteDefinitionLocator {
- Flux<RouteDefinition> getRouteDefinitions();
+ Flux<RouteDefinition> getRouteDefinitions();
}
Additional parameters can be configured for each route using metadata:
@@ -2364,7 +2376,7 @@ route.getMetadata(someKey);To allow for simple configuration in Java, there is a fluent API defined in the RouteLocatorBuilder bean.
The Gateway can be configured to create routes based on services registered with a DiscoveryClient compatible service registry.
To enable this, set spring.cloud.gateway.discovery.locator.enabled=true and make sure a DiscoveryClient implementation is on the classpath and enabled (such as Netflix Eureka, Consul or Zookeeper).
By default the Gateway defines a single predicate and filter for routes created via a DiscoveryClient.
To enable Reactor Netty access logs, set -Dreactor.netty.http.server.accessLogEnabled=true. (It must be a Java System Property, not a Spring Boot property).
The gateway can be configured to control CORS behavior. The "global" CORS configuration is a map of URL patterns to Spring Framework CorsConfiguration.
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.
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.
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:
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.
To retrieve the GatewayFilter factories applied to routes, make a GET request to /actuator/gateway/routefilters. The resulting response is similar to the following:
To clear the routes cache, make a POST request to /actuator/gateway/refresh. The request returns a 200 without response body.
To retrieve the routes defined in the gateway, make a GET request to /actuator/gateway/routes. The resulting response is similar to the following:
To retrieve information about a single route, make a GET request to /actuator/gateway/routes/{id} (e.g., /actuator/gateway/routes/first_route). The resulting response is similar to the following:
To 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).
The table below summarises the Spring Cloud Gateway actuator endpoints. Note that each endpoint has /actuator/gateway as the base-path.
Below are some useful loggers that contain valuable trouble shooting infomration at the DEBUG and TRACE levels.
The Reactor Netty HttpClient and HttpServer can have wiretap enabled. When combined
with setting the reactor.netty log level to DEBUG or TRACE will enable logging of
@@ -2851,19 +2863,19 @@ respectively.
TODO: overview of writing custom integrations
TODO: document writing Custom Route Predicate Factories
In order to write a GatewayFilter you will need to implement GatewayFilterFactory. There is an abstract class called AbstractGatewayFilterFactory which you can extend.
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
- }
+ }
}
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
- }
+ }
}
In order to write a custom global filter, you will need to implement GlobalFilter interface. This will apply the filter to all requests.
TODO: document writing Custom Route Locators and Writers
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).
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.