diff --git a/Finchley.M6/multi/multi__actuator_api.html b/Finchley.M6/multi/multi__actuator_api.html new file mode 100644 index 00000000..02f42ae7 --- /dev/null +++ b/Finchley.M6/multi/multi__actuator_api.html @@ -0,0 +1,3 @@ + + + 111. Actuator API

111. Actuator API

TODO: document the /gateway actuator endpoint

\ No newline at end of file diff --git a/Finchley.M6/multi/multi__appendix_compendium_of_configuration_properties.html b/Finchley.M6/multi/multi__appendix_compendium_of_configuration_properties.html index dd7e9446..2bb5fd1f 100644 --- a/Finchley.M6/multi/multi__appendix_compendium_of_configuration_properties.html +++ b/Finchley.M6/multi/multi__appendix_compendium_of_configuration_properties.html @@ -1,6 +1,6 @@ - Part XIV. Appendix: Compendium of Configuration Properties

Part XIV. Appendix: Compendium of Configuration Properties

NameDefaultDescription

encrypt.fail-on-error

true

Flag to say that a process should fail if there is an encryption or decryption + Part XV. Appendix: Compendium of Configuration Properties

Part XV. Appendix: Compendium of Configuration Properties

NameDefaultDescription

encrypt.fail-on-error

true

Flag to say that a process should fail if there is an encryption or decryption error.

encrypt.key

 

A symmetric key. As a stronger alternative consider using a keystore.

encrypt.key-store.alias

 

Alias for a key in the store.

encrypt.key-store.location

 

Location of the key store file, e.g. classpath:/keystore.jks.

encrypt.key-store.password

 

Password that locks the keystore.

encrypt.key-store.secret

 

Secret protecting the key (defaults to the same as the password).

encrypt.rsa.algorithm

 

The RSA algorithm to use (DEFAULT or OEAP). Once it is set do not change it (or existing ciphers will not a decryptable).

encrypt.rsa.salt

deadbeef

Salt for the random secret used to encrypt cipher text. Once it is set do not change it (or existing ciphers will not a decryptable).

encrypt.rsa.strong

false

Flag to indicate that "strong" AES encryption should be used internally. If @@ -264,4 +264,4 @@ proxy, so they are sharing authentication data. If using a physical URL outside your own domain, then generally it would be a bad idea to leak user credentials.

zuul.servlet-path

/zuul

Path to install Zuul as a servlet (not part of Spring MVC). The servlet is more memory efficient for requests with large bodies, e.g. file uploads.

zuul.ssl-hostname-validation-enabled

true

Flag to say whether the hostname for ssl connections should be verified or not. Default is true. - This should only be used in test setups!

zuul.strip-prefix

true

Flag saying whether to strip the prefix from the path before forwarding.

zuul.trace-request-body

true

Flag to say that request bodies can be traced.

\ No newline at end of file + This should only be used in test setups!

zuul.strip-prefix

true

Flag saying whether to strip the prefix from the path before forwarding.

zuul.trace-request-body

true

Flag to say that request bodies can be traced.

\ No newline at end of file diff --git a/Finchley.M6/multi/multi__building_a_simple_gateway_using_spring_mvc.html b/Finchley.M6/multi/multi__building_a_simple_gateway_using_spring_mvc.html new file mode 100644 index 00000000..d57ccc02 --- /dev/null +++ b/Finchley.M6/multi/multi__building_a_simple_gateway_using_spring_mvc.html @@ -0,0 +1,19 @@ + + + 113. Building a Simple Gateway Using Spring MVC

113. Building a Simple Gateway Using Spring MVC

Spring Cloud Gateway provides a utility object called ProxyExchange which you can use inside a regular Spring MVC handler as a method parameter. It supports basic downstream HTTP exchanges via methods that mirror the HTTP verbs, or forwarding to a local handler via the forward() method.

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

@RestController
+@SpringBootApplication
+public class GatewaySampleApplication {
+
+	@Value("${remote.home}")
+	private URI home;
+
+	@GetMapping("/test")
+	public ResponseEntity<?> proxy(ProxyExchange<Object> proxy) throws Exception {
+		return proxy.uri(home.toString() + "/image/png").get();
+	}
+
+}

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

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

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

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

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

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

\ No newline at end of file diff --git a/Finchley.M6/multi/multi__configuration_2.html b/Finchley.M6/multi/multi__configuration_2.html new file mode 100644 index 00000000..59c3ea66 --- /dev/null +++ b/Finchley.M6/multi/multi__configuration_2.html @@ -0,0 +1,45 @@ + + + 110. Configuration

110. Configuration

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

RouteDefinitionLocator.java.  +

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

+

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

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

application.yml.  +

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

+

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

110.1 Fluent Java Routes API

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

GatewaySampleApplication.java.  +

// static imports from GatewayFilters and RoutePredicates
+@Bean
+public RouteLocator customRouteLocator(ThrottleGatewayFilterFactory throttle) {
+    return Routes.locator()
+            .route("test")
+                .predicate(host("**.abc.org").and(path("/image/png")))
+                .addResponseHeader("X-TestHeader", "foobar")
+                .uri("http://httpbin.org:80")
+            .route("test2")
+                .predicate(path("/image/webp"))
+                .add(addResponseHeader("X-AnotherHeader", "baz"))
+                .uri("http://httpbin.org:80")
+            .route("test3")
+                .order(-1)
+                .predicate(host("**.throttle.org").and(path("/get")))
+                .add(throttle.apply(tuple().of("capacity", 1,
+                     "refillTokens", 1,
+                     "refillPeriod", 10,
+                     "refillUnit", "SECONDS")))
+                .uri("http://httpbin.org:80")
+            .build();
+}

+

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

110.2 DiscoveryClient Route Definition Locator

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

\ No newline at end of file diff --git a/Finchley.M6/multi/multi__developer_guide.html b/Finchley.M6/multi/multi__developer_guide.html new file mode 100644 index 00000000..812e3c08 --- /dev/null +++ b/Finchley.M6/multi/multi__developer_guide.html @@ -0,0 +1,3 @@ + + + 112. Developer Guide

112. Developer Guide

TODO: overview of writing custom integrations

112.1 Writing Custom Route Predicate Factories

TODO: document writing Custom Route Predicate Factories

112.2 Writing Custom GatewayFilter Factories

TODO: document writing Custom GatewayFilter Factories

112.3 Writing Custom Global Filters

TODO: document writing Custom Global Filters

112.4 Writing Custom Route Locators and Writers

TODO: document writing Custom Route Locators and Writers

\ No newline at end of file diff --git a/Finchley.M6/multi/multi__global_filters.html b/Finchley.M6/multi/multi__global_filters.html new file mode 100644 index 00000000..522d97bc --- /dev/null +++ b/Finchley.M6/multi/multi__global_filters.html @@ -0,0 +1,3 @@ + + + 109. Global Filters

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

109.1 Combined Global Filter and GatewayFilter Ordering

TODO: document ordering

109.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 unmodified original url is appended to the list in the ServerWebExchangeUtils.GATEWAY_ORIGINAL_REQUEST_URL_ATTR attribute.

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

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

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

109.6 RouteToRequestUrl Filter

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

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

109.7 Websocket Routing Filter

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

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

\ No newline at end of file diff --git a/Finchley.M6/multi/multi__glossary.html b/Finchley.M6/multi/multi__glossary.html new file mode 100644 index 00000000..95be8d1d --- /dev/null +++ b/Finchley.M6/multi/multi__glossary.html @@ -0,0 +1,3 @@ + + + 105. Glossary

105. Glossary

\ No newline at end of file diff --git a/Finchley.M6/multi/multi__spring_cloud_gateway.html b/Finchley.M6/multi/multi__spring_cloud_gateway.html new file mode 100644 index 00000000..d80e80a6 --- /dev/null +++ b/Finchley.M6/multi/multi__spring_cloud_gateway.html @@ -0,0 +1,3 @@ + + + Part XIV. Spring Cloud Gateway

Part XIV. Spring Cloud Gateway

1.3.5.BUILD-SNAPSHOT

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

\ No newline at end of file diff --git a/Finchley.M6/multi/multi_gateway-how-it-works.html b/Finchley.M6/multi/multi_gateway-how-it-works.html new file mode 100644 index 00000000..d11213c2 --- /dev/null +++ b/Finchley.M6/multi/multi_gateway-how-it-works.html @@ -0,0 +1,3 @@ + + + 106. How It Works

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

\ No newline at end of file diff --git a/Finchley.M6/multi/multi_gateway-request-predicates-factories.html b/Finchley.M6/multi/multi_gateway-request-predicates-factories.html new file mode 100644 index 00000000..6a4313a8 --- /dev/null +++ b/Finchley.M6/multi/multi_gateway-request-predicates-factories.html @@ -0,0 +1,102 @@ + + + 107. Route Predicate Factories

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

107.1 After Route Predicate Factory

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

application.yml.  +

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

+

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

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

application.yml.  +

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

+

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

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

application.yml.  +

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

+

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

107.4 Cookie Route Predicate Factory

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

application.yml.  +

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

+

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

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

application.yml.  +

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

+

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

107.6 Host Route Predicate Factory

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

application.yml.  +

spring:
+  cloud:
+    gateway:
+      routes:
+      - id: host_route
+        uri: http://example.org
+        predicates:
+        - Host=**.somehost.org

+

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

107.7 Method Route Predicate Factory

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

application.yml.  +

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

+

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

107.8 Path Route Predicate Factory

The Path Route Predicate Factory takes one parameter: a Spring PathMatcher pattern.

application.yml.  +

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

+

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

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

107.9 Query Route Predicate Factory

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

application.yml.  +

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

+

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

application.yml.  +

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

+

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

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

application.yml.  +

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

+

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

\ No newline at end of file diff --git a/Finchley.M6/multi/multi_gateway-route-filters.html b/Finchley.M6/multi/multi_gateway-route-filters.html new file mode 100644 index 00000000..33c5faa5 --- /dev/null +++ b/Finchley.M6/multi/multi_gateway-route-filters.html @@ -0,0 +1,172 @@ + + + 108. GatewayFilter Factories

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

108.1 AddRequestHeader GatewayFilter Factory

The AddRequestHeader GatewayFilter Factory takes a name and value parameter.

application.yml.  +

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

+

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

108.2 AddRequestParameter GatewayFilter Factory

The AddRequestParameter GatewayFilter Factory takes a name and value parameter.

application.yml.  +

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

+

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

108.3 AddResponseHeader GatewayFilter Factory

The AddResponseHeader GatewayFilter Factory takes a name and value parameter.

application.yml.  +

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

+

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

108.4 Hystrix GatewayFilter Factory

The Hystrix GatewayFilter Factory takes a single name parameters, which is the name of the HystrixCommand. (More options might be added in future releases).

application.yml.  +

spring:
+  cloud:
+    gateway:
+      routes:
+      - id: hytstrix_route
+        uri: http://example.org
+        filters:
+        - Hystrix=myCommandName

+

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

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

application.yml.  +

spring:
+  cloud:
+    gateway:
+      routes:
+      - id: hytstrix_route
+        uri: http://example.org
+        filters:
+        - name: Hystrix
+          args:
+            name: fallbackcmd
+            fallbackUri: forward:/fallbackcontroller
+
+This will forward to the `/fallbackcontroller` when the Hystrix fallback is called.

+

108.5 PrefixPath GatewayFilter Factory

The PrefixPath GatewayFilter Factory takes a single prefix parameter.

application.yml.  +

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

+

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

108.6 PreserveHostHeader GatewayFilter Factory

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

application.yml.  +

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

+

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

108.7 RequestRateLimiter GatewayFilter Factory

The RequestRateLimiter GatewayFilter Factory takes three parameters: replenishRate, burstCapacity & keyResolverName.

replenishRate is how many requests per second do you want a user to be allowed to do.

burstCapacity TODO: document burst capacity

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

KeyResolver.java.  +

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

+

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

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

application.yml.  +

spring:
+  cloud:
+    gateway:
+      routes:
+      - id: requestratelimiter_route
+        uri: http://example.org
+        filters:
+        - RequestRateLimiter=10, 20, #{@userKeyResolver}

+

Config.java.  +

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

+

This defines a request rate limit of 10 per user. The KeyResolver is a simple one that gets the user request parameter (note: this is not recommended for production).

108.8 RedirectTo GatewayFilter Factory

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

application.yml.  +

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

+

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

108.9 RemoveNonProxyHeaders GatewayFilter Factory

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

The default removed headers are:

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

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

108.10 RemoveRequestHeader GatewayFilter Factory

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

application.yml.  +

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

+

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

108.11 RemoveResponseHeader GatewayFilter Factory

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

application.yml.  +

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

+

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

108.12 RewritePath GatewayFilter Factory

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

application.yml.  +

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

+

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

108.13 SaveSession GatewayFilter Factory

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

application.yml.  +

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

+

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

108.14 SecureHeaders GatewayFilter Factory

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

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

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

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

Property to change:

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

108.15 SetPath GatewayFilter Factory

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

application.yml.  +

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

+

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

108.16 SetResponseHeader GatewayFilter Factory

The SetResponseHeader GatewayFilter Factory takes name and value parameters.

application.yml.  +

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

+

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

108.17 SetStatus GatewayFilter Factory

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

application.yml.  +

spring:
+  cloud:
+    gateway:
+      routes:
+      - id: setstatusstring_route
+        uri: http://example.org
+        filters:
+        - SetStatus=BAD_REQUEST
+      - id: setstatusint_route
+        uri: http://example.org
+        filters:
+        - SetStatus=401

+

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

\ No newline at end of file diff --git a/Finchley.M6/multi/multi_gateway-starter.html b/Finchley.M6/multi/multi_gateway-starter.html new file mode 100644 index 00000000..af5d0b4c --- /dev/null +++ b/Finchley.M6/multi/multi_gateway-starter.html @@ -0,0 +1,5 @@ + + + 104. How to Include Spring Cloud Gateway

104. How to Include Spring Cloud Gateway

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

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

\ No newline at end of file diff --git a/Finchley.M6/multi/multi_spring-cloud.html b/Finchley.M6/multi/multi_spring-cloud.html index 1620164f..e0042112 100644 --- a/Finchley.M6/multi/multi_spring-cloud.html +++ b/Finchley.M6/multi/multi_spring-cloud.html @@ -1,3 +1,3 @@ - Spring Cloud

Spring Cloud


Table of Contents

1. Features
I. Cloud Native Applications
2. Spring Cloud Context: Application Context Services
2.1. The Bootstrap Application Context
2.2. Application Context Hierarchies
2.3. Changing the Location of Bootstrap Properties
2.4. Overriding the Values of Remote Properties
2.5. Customizing the Bootstrap Configuration
2.6. Customizing the Bootstrap Property Sources
2.7. Environment Changes
2.8. Refresh Scope
2.9. Encryption and Decryption
2.10. Endpoints
3. Spring Cloud Commons: Common Abstractions
3.1. @EnableDiscoveryClient
3.1.1. Health Indicator
3.2. ServiceRegistry
3.2.1. ServiceRegistry Auto-Registration
3.2.2. Service Registry Actuator Endpoint
3.3. Spring RestTemplate as a Load Balancer Client
3.4. Spring WebClient as a Load Balancer Client
3.4.1. Retrying Failed Requests
3.5. Multiple RestTemplate objects
3.6. Spring WebFlux WebClient as a Load Balancer Client
3.7. Ignore Network Interfaces
3.8. HTTP Client Factories
3.9. Enabled Features
3.9.1. Feature types
3.9.2. Declaring features
II. Spring Cloud Config
4. Quick Start
4.1. Client Side Usage
5. Spring Cloud Config Server
5.1. Environment Repository
5.1.1. Git Backend
Placeholders in Git URI
Pattern Matching and Multiple Repositories
Authentication
Authentication with AWS CodeCommit
Git SSH configuration using properties
Placeholders in Git Search Paths
Force pull in Git Repositories
5.1.2. Version Control Backend Filesystem Use
5.1.3. File System Backend
5.1.4. Vault Backend
Multiple Properties Sources
5.1.5. Sharing Configuration With All Applications
File Based Repositories
Vault Server
5.1.6. JDBC Backend
5.1.7. Composite Environment Repositories
Custom Composite Environment Repositories
5.1.8. Property Overrides
5.2. Health Indicator
5.3. Security
5.4. Encryption and Decryption
5.5. Key Management
5.6. Creating a Key Store for Testing
5.7. Using Multiple Keys and Key Rotation
5.8. Serving Encrypted Properties
6. Serving Alternative Formats
7. Serving Plain Text
8. Embedding the Config Server
9. Push Notifications and Spring Cloud Bus
10. Spring Cloud Config Client
10.1. Config First Bootstrap
10.2. Discovery First Bootstrap
10.3. Config Client Fail Fast
10.4. Config Client Retry
10.5. Locating Remote Configuration Resources
10.6. Security
10.6.1. Health Indicator
10.6.2. Providing A Custom RestTemplate
10.6.3. Vault
10.7. Vault
10.7.1. Nested Keys In Vault
III. Spring Cloud Netflix
11. Service Discovery: Eureka Clients
11.1. How to Include Eureka Client
11.2. Registering with Eureka
11.3. Authenticating with the Eureka Server
11.4. Status Page and Health Indicator
11.5. Registering a Secure Application
11.6. Eureka’s Health Checks
11.7. Eureka Metadata for Instances and Clients
11.7.1. Using Eureka on Cloudfoundry
11.7.2. Using Eureka on AWS
11.7.3. Changing the Eureka Instance ID
11.8. Using the EurekaClient
11.8.1. EurekaClient without Jersey
11.9. Alternatives to the native Netflix EurekaClient
11.10. Why is it so Slow to Register a Service?
11.11. Zones
12. Service Discovery: Eureka Server
12.1. How to Include Eureka Server
12.2. How to Run a Eureka Server
12.3. High Availability, Zones and Regions
12.4. Standalone Mode
12.5. Peer Awareness
12.6. Prefer IP Address
13. Circuit Breaker: Hystrix Clients
13.1. How to Include Hystrix
13.2. Propagating the Security Context or using Spring Scopes
13.3. Health Indicator
13.4. Hystrix Metrics Stream
14. Circuit Breaker: Hystrix Dashboard
15. Hystrix Timeouts And Ribbon Clients
15.1. How to Include Hystrix Dashboard
15.2. Turbine
15.3. Turbine Stream
16. Client Side Load Balancer: Ribbon
16.1. How to Include Ribbon
16.2. Customizing the Ribbon Client
16.3. Customizing default for all Ribbon Clients
16.4. Customizing the Ribbon Client using properties
16.5. Using Ribbon with Eureka
16.6. Example: How to Use Ribbon Without Eureka
16.7. Example: Disable Eureka use in Ribbon
16.8. Using the Ribbon API Directly
16.9. Caching of Ribbon Configuration
16.10. How to Configure Hystrix thread pools
16.11. How to Provide a Key to Ribbon’s IRule
17. Declarative REST Client: Feign
17.1. How to Include Feign
17.2. Overriding Feign Defaults
17.3. Creating Feign Clients Manually
17.4. Feign Hystrix Support
17.5. Feign Hystrix Fallbacks
17.6. Feign and @Primary
17.7. Feign Inheritance Support
17.8. Feign request/response compression
17.9. Feign logging
18. External Configuration: Archaius
19. Router and Filter: Zuul
19.1. How to Include Zuul
19.2. Embedded Zuul Reverse Proxy
19.3. Zuul Http Client
19.4. Cookies and Sensitive Headers
19.5. Ignored Headers
19.6. Management Endpoints
19.6.1. Routes Endpoint
19.6.2. Filters Endpoint
19.7. Strangulation Patterns and Local Forwards
19.8. Uploading Files through Zuul
19.9. Query String Encoding
19.10. Plain Embedded Zuul
19.11. Disable Zuul Filters
19.12. Providing Hystrix Fallbacks For Routes
19.13. Zuul Timeouts
19.14. Rewriting Location header
19.15. Zuul Developer Guide
19.15.1. The Zuul Servlet
19.15.2. Zuul RequestContext
19.15.3. @EnableZuulProxy vs. @EnableZuulServer
19.15.4. @EnableZuulServer Filters
19.15.5. @EnableZuulProxy Filters
19.15.6. Custom Zuul Filter examples
19.15.7. How to Write a Pre Filter
19.15.8. How to Write a Route Filter
19.15.9. How to Write a Post Filter
19.15.10. How Zuul Errors Work
19.15.11. Zuul Eager Application Context Loading
20. Polyglot support with Sidecar
21. Metrics: Spectator, Servo, and Atlas
21.1. Dimensional vs. Hierarchical Metrics
21.2. Default Metrics Collection
21.3. Metrics Collection: Spectator
21.3.1. Spectator Counter
21.3.2. Spectator Timer
21.3.3. Spectator Gauge
21.3.4. Spectator Distribution Summaries
21.4. Metrics Collection: Servo
21.4.1. Creating Servo Monitors
21.5. Metrics Backend: Atlas
21.5.1. Global tags
21.5.2. Using Atlas
21.6. Retrying Failed Requests
21.6.1. BackOff Policies
21.6.2. Configuration
21.6.3. Zuul
22. HTTP Clients
IV. Spring Cloud Stream
23. Introducing Spring Cloud Stream
24. Main Concepts
24.1. Application Model
24.1.1. Fat JAR
24.2. The Binder Abstraction
24.3. Persistent Publish-Subscribe Support
24.4. Consumer Groups
24.5. Consumer Types
24.5.1. Durability
24.6. Partitioning Support
25. Programming Model
25.1. Declaring and Binding Producers and Consumers
25.1.1. Triggering Binding Via @EnableBinding
25.1.2. @Input and @Output
Customizing Channel Names
Source, Sink, and Processor
25.1.3. Accessing Bound Channels
Injecting the Bound Interfaces
Injecting Channels Directly
25.1.4. Producing and Consuming Messages
Native Spring Integration Support
Spring Integration Error Channel Support
Message Channel Binders and Error Channels
Using @StreamListener for Automatic Content Type Handling
Using @StreamListener for dispatching messages to multiple methods
Using Polled Consumers
25.1.5. Reactive Programming Support
Reactor-based handlers
RxJava 1.x support
Reactive Sources
25.1.6. Aggregation
Configuring aggregate application
Configuring binding service properties for non self contained aggregate application
26. Binders
26.1. Producers and Consumers
26.2. Binder SPI
26.3. Binder Detection
26.3.1. Classpath Detection
26.4. Multiple Binders on the Classpath
26.5. Connecting to Multiple Systems
26.6. Binder configuration properties
27. Configuration Options
27.1. Spring Cloud Stream Properties
27.2. Binding Properties
27.2.1. Properties for Use of Spring Cloud Stream
27.2.2. Consumer properties
27.2.3. Producer Properties
27.3. Using dynamically bound destinations
28. Content Type and Transformation
28.1. MIME types
28.2. Channel contentType and Message Headers
28.3. ContentType handling for output channels
28.4. ContentType handling for input channels
28.5. Customizing message conversion
28.6. @StreamListener and Message Conversion
29. Schema evolution support
29.1. Apache Avro Message Converters
29.2. Converters with schema support
29.3. Schema Registry Support
29.4. Schema Registry Server
29.4.1. Schema Registry Server API
POST /
GET /{subject}/{format}/{version}
GET /{subject}/{format}
GET /schemas/{id}
DELETE /{subject}/{format}/{version}
DELETE /schemas/{id}
DELETE /{subject}
29.5. Schema Registry Client
29.5.1. Using Confluent’s Schema Registry
29.5.2. Schema Registry Client properties
29.6. Avro Schema Registry Client Message Converters
29.6.1. Avro Schema Registry Message Converter properties
29.7. Schema Registration and Resolution
29.7.1. Schema Registration Process (Serialization)
29.7.2. Schema Resolution Process (Deserialization)
30. Inter-Application Communication
30.1. Connecting Multiple Application Instances
30.2. Instance Index and Instance Count
30.3. Partitioning
30.3.1. Configuring Output Bindings for Partitioning
Configuring Input Bindings for Partitioning
31. Testing
31.1. Disabling the test binder autoconfiguration
32. Health Indicator
33. Metrics Emitter
34. Samples
35. Getting Started
35.1. Deploying Stream applications on CloudFoundry
V. Binder Implementations
36. Apache Kafka Binder
36.1. Usage
36.2. Apache Kafka Binder Overview
36.3. Configuration Options
36.3.1. Kafka Binder Properties
36.3.2. Kafka Consumer Properties
36.3.3. Kafka Producer Properties
36.3.4. Usage examples
Example: Setting autoCommitOffset false and relying on manual acking.
Example: security configuration
Example: Pausing and Resuming the Consumer
Using the binder with Apache Kafka 0.10
Excluding Kafka broker jar from the classpath of the binder based application
36.4. Kafka Streams Binding Capabilities of Spring Cloud Stream
36.4.1. Usage example of high level streams DSL
36.4.2. Message conversion in Spring Cloud Stream Kafka Streams applications
36.4.3. Support for branching in Kafka Streams API
36.4.4. Support for interactive queries
36.4.5. Kafka Streams properties
36.5. Error Channels
36.6. Kafka Metrics
36.7. Dead-Letter Topic Processing
36.8. Partitioning with the Kafka Binder
37. RabbitMQ Binder
37.1. Usage
37.2. RabbitMQ Binder Overview
37.3. Configuration Options
37.3.1. RabbitMQ Binder Properties
37.3.2. RabbitMQ Consumer Properties
37.3.3. Rabbit Producer Properties
37.4. Retry With the RabbitMQ Binder
37.4.1. Overview
37.4.2. Putting it All Together
37.5. Error Channels
37.6. Dead-Letter Queue Processing
37.6.1. Non-Partitioned Destinations
37.6.2. Partitioned Destinations
republishToDlq=false
republishToDlq=true
37.7. Partitioning with the RabbitMQ Binder
VI. Spring Cloud Bus
38. Quick Start
39. Addressing an Instance
40. Addressing all instances of a service
41. Service ID must be unique
42. Customizing the Message Broker
43. Tracing Bus Events
44. Broadcasting Your Own Events
44.1. Registering events in custom packages
VII. Spring Cloud Sleuth
45. Introduction
45.1. Terminology
45.2. Purpose
45.2.1. Distributed tracing with Zipkin
45.2.2. Visualizing errors
45.2.3. Distributed tracing with Brave
45.2.4. Live examples
45.2.5. Log correlation
JSON Logback with Logstash
45.2.6. Propagating Span Context
Baggage vs. Span Tags
45.3. Adding to the project
45.3.1. Only Sleuth (log correlation)
45.3.2. Sleuth with Zipkin via HTTP
45.3.3. Sleuth with Zipkin via RabbitMQ or Kafka
46. Additional resources
47. Features
47.1. Introduction to Brave
47.1.1. Tracing
47.1.2. Tracing
47.1.3. Local Tracing
47.1.4. Customizing spans
47.1.5. Implicitly looking up the current span
47.1.6. RPC tracing
One-Way tracing
48. Sampling
48.1. Declarative sampling
48.2. Custom sampling
48.3. Sampling in Spring Cloud Sleuth
49. Propagation
49.1. Propagating extra fields
49.1.1. Prefixed fields
49.1.2. Extracting a propagated context
49.1.3. Sharing span IDs between client and server
49.1.4. Implementing Propagation
50. Current Tracing Component
51. Current Span
51.1. Setting a span in scope manually
52. Instrumentation
53. Span lifecycle
53.1. Creating and finishing spans
53.2. Continuing spans
53.3. Creating spans with an explicit parent
54. Naming spans
54.1. @SpanName annotation
54.2. toString() method
55. Managing spans with annotations
55.1. Rationale
55.2. Creating new spans
55.3. Continuing spans
55.4. More advanced tag setting
55.4.1. Custom extractor
55.4.2. Resolving expressions for value
55.4.3. Using toString method
56. Customizations
56.1. Spring Integration
56.2. HTTP
56.3. TraceFilter
56.4. Custom service name
56.5. Customization of reported spans
56.6. Host locator
57. Sending spans to Zipkin
58. Zipkin Stream Span Consumer
59. Integrations
59.1. OpenTracing
59.2. Runnable and Callable
59.3. Hystrix
59.3.1. Custom Concurrency Strategy
59.3.2. Manual Command setting
59.4. RxJava
59.5. HTTP integration
59.5.1. HTTP Filter
59.5.2. HandlerInterceptor
59.5.3. Async Servlet support
59.5.4. WebFlux support
59.6. HTTP client integration
59.6.1. Synchronous Rest Template
59.6.2. Asynchronous Rest Template
Multiple Asynchronous Rest Templates
59.6.3. WebClient
59.6.4. Traverson
59.7. Feign
59.8. Asynchronous communication
59.8.1. @Async annotated methods
59.8.2. @Scheduled annotated methods
59.8.3. Executor, ExecutorService and ScheduledExecutorService
Customization of Executors
59.9. Messaging
59.10. Zuul
60. Running examples
VIII. Spring Cloud Consul
61. Install Consul
62. Consul Agent
63. Service Discovery with Consul
63.1. How to activate
63.2. Registering with Consul
63.3. HTTP Health Check
63.3.1. Metadata and Consul tags
63.3.2. Making the Consul Instance ID Unique
63.4. Looking up services
63.4.1. Using Ribbon
63.4.2. Using the DiscoveryClient
64. Distributed Configuration with Consul
64.1. How to activate
64.2. Customizing
64.3. Config Watch
64.4. YAML or Properties with Config
64.5. git2consul with Config
64.6. Fail Fast
65. Consul Retry
66. Spring Cloud Bus with Consul
66.1. How to activate
67. Circuit Breaker with Hystrix
68. Hystrix metrics aggregation with Turbine and Consul
IX. Spring Cloud Zookeeper
69. Install Zookeeper
70. Service Discovery with Zookeeper
70.1. How to activate
70.2. Registering with Zookeeper
70.3. Using the DiscoveryClient
71. Using Spring Cloud Zookeeper with Spring Cloud Netflix Components
71.1. Ribbon with Zookeeper
72. Spring Cloud Zookeeper and Service Registry
72.1. Instance Status
73. Zookeeper Dependencies
73.1. Using the Zookeeper Dependencies
73.2. How to activate Zookeeper Dependencies
73.3. Setting up Zookeeper Dependencies
73.3.1. Aliases
73.3.2. Path
73.3.3. Load balancer type
73.3.4. Content-Type template and version
73.3.5. Default headers
73.3.6. Obligatory dependencies
73.3.7. Stubs
73.4. Configuring Spring Cloud Zookeeper Dependencies
74. Spring Cloud Zookeeper Dependency Watcher
74.1. How to activate
74.2. Registering a listener
74.3. Presence Checker
75. Distributed Configuration with Zookeeper
75.1. How to activate
75.2. Customizing
75.3. ACLs
X. Spring Cloud Security
76. Quickstart
76.1. OAuth2 Single Sign On
76.2. OAuth2 Protected Resource
77. More Detail
77.1. Single Sign On
77.2. Token Relay
77.2.1. Client Token Relay
77.2.2. Client Token Relay in Zuul Proxy
77.2.3. Resource Server Token Relay
78. Configuring Authentication Downstream of a Zuul Proxy
XI. Spring Cloud for Cloud Foundry
79. Discovery
80. Single Sign On
XII. Spring Cloud Contract
81. Spring Cloud Contract
82. Spring Cloud Contract Verifier Introduction
82.1. Why a Contract Verifier?
82.1.1. Testing issues
82.2. Purposes
82.3. How It Works
82.3.1. Defining the contract
82.3.2. Client Side
82.3.3. Server Side
82.4. Step-by-step Guide to Consumer Driven Contracts (CDC)
82.4.1. Technical note
82.4.2. Consumer side (Loan Issuance)
82.4.3. Producer side (Fraud Detection server)
82.4.4. Consumer Side (Loan Issuance) Final Step
82.5. Dependencies
82.6. Additional Links
82.6.1. Spring Cloud Contract video
82.6.2. Readings
82.7. Samples
83. Spring Cloud Contract FAQ
83.1. Why use Spring Cloud Contract Verifier and not X ?
83.2. I don’t want to write a contract in Groovy!
83.3. What is this value(consumer(), producer()) ?
83.4. How to do Stubs versioning?
83.4.1. API Versioning
83.4.2. JAR versioning
83.4.3. Dev or prod stubs
83.5. Common repo with contracts
83.5.1. Repo structure
83.5.2. Workflow
83.5.3. Consumer
83.5.4. Producer
83.6. Can I have multiple base classes for tests?
83.7. How can I debug the request/response being sent by the generated tests client?
83.7.1. How can I debug the mapping/request/response being sent by WireMock?
83.7.2. How can I see what got registered in the HTTP server stub?
83.7.3. Can I reference the request from the response?
83.7.4. Can I reference text from file?
84. Spring Cloud Contract Verifier Setup
84.1. Gradle Project
84.1.1. Prerequisites
84.1.2. Add Gradle Plugin with Dependencies
84.1.3. Gradle and Rest Assured 2.0
84.1.4. Snapshot Versions for Gradle
84.1.5. Add stubs
84.1.6. Run the Plugin
84.1.7. Default Setup
84.1.8. Configure Plugin
84.1.9. Configuration Options
84.1.10. Single Base Class for All Tests
84.1.11. Different Base Classes for Contracts
84.1.12. Invoking Generated Tests
84.1.13. Spring Cloud Contract Verifier on the Consumer Side
84.2. Maven Project
84.2.1. Add maven plugin
84.2.2. Maven and Rest Assured 2.0
84.2.3. Snapshot versions for Maven
84.2.4. Add stubs
84.2.5. Run plugin
84.2.6. Configure plugin
84.2.7. Configuration Options
84.2.8. Single Base Class for All Tests
84.2.9. Different base classes for contracts
84.2.10. Invoking generated tests
84.2.11. Maven Plugin and STS
84.2.12. Spring Cloud Contract Verifier on the Consumer Side
84.3. Stubs and Transitive Dependencies
84.4. Scenarios
84.5. Docker Project
84.5.1. Short intro to Maven, JARs and Binary storage
84.5.2. How it works
Environment Variables
84.5.3. Example of usage
84.5.4. Server side (nodejs)
85. Spring Cloud Contract Verifier Messaging
85.1. Integrations
85.2. Manual Integration Testing
85.3. Publisher-Side Test Generation
85.3.1. Scenario 1: No Input Message
85.3.2. Scenario 2: Output Triggered by Input
85.3.3. Scenario 3: No Output Message
85.4. Consumer Stub Generation
86. Spring Cloud Contract Stub Runner
86.1. Snapshot versions
86.2. Publishing Stubs as JARs
86.3. Stub Runner Core
86.3.1. Retrieving stubs
Stub downloading
Classpath scanning
86.3.2. Running stubs
Limitations
Running using main app
HTTP Stubs
Viewing registered mappings
Messaging Stubs
86.4. Stub Runner JUnit Rule
86.4.1. Maven settings
86.4.2. Providing fixed ports
86.4.3. Fluent API
86.4.4. Stub Runner with Spring
86.5. Stub Runner Spring Cloud
86.5.1. Stubbing Service Discovery
Test profiles and service discovery
86.5.2. Additional Configuration
86.6. Stub Runner Boot Application
86.6.1. How to use it?
Stub Runner Server
Spring Cloud CLI
86.6.2. Endpoints
HTTP
Messaging
86.6.3. Example
86.6.4. Stub Runner Boot with Service Discovery
86.7. Stubs Per Consumer
86.8. Common
86.8.1. Common Properties for JUnit and Spring
86.8.2. Stub Runner Stubs IDs
86.9. Stub Runner Docker
86.9.1. How to use it
86.9.2. Example of client side usage in a non JVM project
87. Stub Runner for Messaging
87.1. Stub triggering
87.1.1. Trigger by Label
87.1.2. Trigger by Group and Artifact Ids
87.1.3. Trigger by Artifact Ids
87.1.4. Trigger All Messages
87.2. Stub Runner Integration
87.2.1. Adding the Runner to the Project
87.2.2. Disabling the functionality
Scenario 1 (no input message)
Scenario 2 (output triggered by input)
Scenario 3 (input with no output)
87.3. Stub Runner Stream
87.3.1. Adding the Runner to the Project
87.3.2. Disabling the functionality
Scenario 1 (no input message)
Scenario 2 (output triggered by input)
Scenario 3 (input with no output)
87.4. Stub Runner Spring AMQP
87.4.1. Adding the Runner to the Project
Triggering the message
Spring AMQP Test Configuration
88. Contract DSL
88.1. Limitations
88.2. Common Top-Level elements
88.2.1. Description
88.2.2. Name
88.2.3. Ignoring Contracts
88.2.4. Passing Values from Files
88.2.5. HTTP Top-Level Elements
88.3. Request
88.4. Response
88.5. Dynamic properties
88.5.1. Dynamic properties inside the body
88.5.2. Regular expressions
88.5.3. Passing Optional Parameters
88.5.4. Executing Custom Methods on the Server Side
88.5.5. Referencing the Request from the Response
88.5.6. Registering Your Own WireMock Extension
88.5.7. Dynamic Properties in the Matchers Sections
88.6. JAX-RS Support
88.7. Async Support
88.8. Working with Context Paths
88.9. Messaging Top-Level Elements
88.9.1. Output Triggered by a Method
88.9.2. Output Triggered by a Message
88.9.3. Consumer/Producer
88.9.4. Common
88.10. Multiple Contracts in One File
89. Customization
89.1. Extending the DSL
89.1.1. Common JAR
89.1.2. Adding the Dependency to the Project
89.1.3. Test the Dependency in the Project’s Dependencies
89.1.4. Test a Dependency in the Plugin’s Dependencies
89.1.5. Referencing classes in DSLs
90. Using the Pluggable Architecture
90.1. Custom Contract Converter
90.1.1. Pact Converter
90.1.2. Pact Contract
90.1.3. Pact for Producers
90.1.4. Pact for Consumers
90.2. Using the Custom Test Generator
90.3. Using the Custom Stub Generator
90.4. Using the Custom Stub Runner
90.5. Using the Custom Stub Downloader
91. Spring Cloud Contract WireMock
91.1. Registering Stubs Automatically
91.2. Using Files to Specify the Stub Bodies
91.3. Alternative: Using JUnit Rules
91.4. Relaxed SSL Validation for Rest Template
91.5. WireMock and Spring MVC Mocks
91.6. Customization of WireMock configuration
91.7. Generating Stubs using REST Docs
91.8. Generating Contracts by Using REST Docs
92. Migrations
92.1. 1.0.x → 1.1.x
92.1.1. New structure of generated stubs
92.2. 1.1.x → 1.2.x
92.2.1. Custom HttpServerStub
92.2.2. New packages for generated tests
92.2.3. New Methods in TemplateProcessor
92.2.4. RestAssured 3.0
92.3. 1.2.x → 2.0.x
92.3.1. No Camel support
93. Links
XIII. Spring Cloud Vault
94. Quick Start
95. Client Side Usage
95.1. Authentication
96. Authentication methods
96.1. Token authentication
96.2. AppId authentication
96.2.1. Custom UserId
96.3. AppRole authentication
96.4. AWS-EC2 authentication
96.5. AWS-IAM authentication
96.6. TLS certificate authentication
96.7. Cubbyhole authentication
96.8. Kubernetes authentication
97. Secret Backends
97.1. Generic Backend
97.2. Consul
97.3. RabbitMQ
97.4. AWS
98. Database backends
98.1. Database
98.2. Apache Cassandra
98.3. MongoDB
98.4. MySQL
98.5. PostgreSQL
99. Configure PropertySourceLocator behavior
100. Service Registry Configuration
101. Vault Client Fail Fast
102. Vault Client SSL configuration
103. Lease lifecycle management (renewal and revocation)
XIV. Appendix: Compendium of Configuration Properties
\ No newline at end of file + Spring Cloud

Spring Cloud


Table of Contents

1. Features
I. Cloud Native Applications
2. Spring Cloud Context: Application Context Services
2.1. The Bootstrap Application Context
2.2. Application Context Hierarchies
2.3. Changing the Location of Bootstrap Properties
2.4. Overriding the Values of Remote Properties
2.5. Customizing the Bootstrap Configuration
2.6. Customizing the Bootstrap Property Sources
2.7. Environment Changes
2.8. Refresh Scope
2.9. Encryption and Decryption
2.10. Endpoints
3. Spring Cloud Commons: Common Abstractions
3.1. @EnableDiscoveryClient
3.1.1. Health Indicator
3.2. ServiceRegistry
3.2.1. ServiceRegistry Auto-Registration
3.2.2. Service Registry Actuator Endpoint
3.3. Spring RestTemplate as a Load Balancer Client
3.4. Spring WebClient as a Load Balancer Client
3.4.1. Retrying Failed Requests
3.5. Multiple RestTemplate objects
3.6. Spring WebFlux WebClient as a Load Balancer Client
3.7. Ignore Network Interfaces
3.8. HTTP Client Factories
3.9. Enabled Features
3.9.1. Feature types
3.9.2. Declaring features
II. Spring Cloud Config
4. Quick Start
4.1. Client Side Usage
5. Spring Cloud Config Server
5.1. Environment Repository
5.1.1. Git Backend
Placeholders in Git URI
Pattern Matching and Multiple Repositories
Authentication
Authentication with AWS CodeCommit
Git SSH configuration using properties
Placeholders in Git Search Paths
Force pull in Git Repositories
5.1.2. Version Control Backend Filesystem Use
5.1.3. File System Backend
5.1.4. Vault Backend
Multiple Properties Sources
5.1.5. Sharing Configuration With All Applications
File Based Repositories
Vault Server
5.1.6. JDBC Backend
5.1.7. Composite Environment Repositories
Custom Composite Environment Repositories
5.1.8. Property Overrides
5.2. Health Indicator
5.3. Security
5.4. Encryption and Decryption
5.5. Key Management
5.6. Creating a Key Store for Testing
5.7. Using Multiple Keys and Key Rotation
5.8. Serving Encrypted Properties
6. Serving Alternative Formats
7. Serving Plain Text
8. Embedding the Config Server
9. Push Notifications and Spring Cloud Bus
10. Spring Cloud Config Client
10.1. Config First Bootstrap
10.2. Discovery First Bootstrap
10.3. Config Client Fail Fast
10.4. Config Client Retry
10.5. Locating Remote Configuration Resources
10.6. Security
10.6.1. Health Indicator
10.6.2. Providing A Custom RestTemplate
10.6.3. Vault
10.7. Vault
10.7.1. Nested Keys In Vault
III. Spring Cloud Netflix
11. Service Discovery: Eureka Clients
11.1. How to Include Eureka Client
11.2. Registering with Eureka
11.3. Authenticating with the Eureka Server
11.4. Status Page and Health Indicator
11.5. Registering a Secure Application
11.6. Eureka’s Health Checks
11.7. Eureka Metadata for Instances and Clients
11.7.1. Using Eureka on Cloudfoundry
11.7.2. Using Eureka on AWS
11.7.3. Changing the Eureka Instance ID
11.8. Using the EurekaClient
11.8.1. EurekaClient without Jersey
11.9. Alternatives to the native Netflix EurekaClient
11.10. Why is it so Slow to Register a Service?
11.11. Zones
12. Service Discovery: Eureka Server
12.1. How to Include Eureka Server
12.2. How to Run a Eureka Server
12.3. High Availability, Zones and Regions
12.4. Standalone Mode
12.5. Peer Awareness
12.6. Prefer IP Address
13. Circuit Breaker: Hystrix Clients
13.1. How to Include Hystrix
13.2. Propagating the Security Context or using Spring Scopes
13.3. Health Indicator
13.4. Hystrix Metrics Stream
14. Circuit Breaker: Hystrix Dashboard
15. Hystrix Timeouts And Ribbon Clients
15.1. How to Include Hystrix Dashboard
15.2. Turbine
15.3. Turbine Stream
16. Client Side Load Balancer: Ribbon
16.1. How to Include Ribbon
16.2. Customizing the Ribbon Client
16.3. Customizing default for all Ribbon Clients
16.4. Customizing the Ribbon Client using properties
16.5. Using Ribbon with Eureka
16.6. Example: How to Use Ribbon Without Eureka
16.7. Example: Disable Eureka use in Ribbon
16.8. Using the Ribbon API Directly
16.9. Caching of Ribbon Configuration
16.10. How to Configure Hystrix thread pools
16.11. How to Provide a Key to Ribbon’s IRule
17. Declarative REST Client: Feign
17.1. How to Include Feign
17.2. Overriding Feign Defaults
17.3. Creating Feign Clients Manually
17.4. Feign Hystrix Support
17.5. Feign Hystrix Fallbacks
17.6. Feign and @Primary
17.7. Feign Inheritance Support
17.8. Feign request/response compression
17.9. Feign logging
18. External Configuration: Archaius
19. Router and Filter: Zuul
19.1. How to Include Zuul
19.2. Embedded Zuul Reverse Proxy
19.3. Zuul Http Client
19.4. Cookies and Sensitive Headers
19.5. Ignored Headers
19.6. Management Endpoints
19.6.1. Routes Endpoint
19.6.2. Filters Endpoint
19.7. Strangulation Patterns and Local Forwards
19.8. Uploading Files through Zuul
19.9. Query String Encoding
19.10. Plain Embedded Zuul
19.11. Disable Zuul Filters
19.12. Providing Hystrix Fallbacks For Routes
19.13. Zuul Timeouts
19.14. Rewriting Location header
19.15. Zuul Developer Guide
19.15.1. The Zuul Servlet
19.15.2. Zuul RequestContext
19.15.3. @EnableZuulProxy vs. @EnableZuulServer
19.15.4. @EnableZuulServer Filters
19.15.5. @EnableZuulProxy Filters
19.15.6. Custom Zuul Filter examples
19.15.7. How to Write a Pre Filter
19.15.8. How to Write a Route Filter
19.15.9. How to Write a Post Filter
19.15.10. How Zuul Errors Work
19.15.11. Zuul Eager Application Context Loading
20. Polyglot support with Sidecar
21. Metrics: Spectator, Servo, and Atlas
21.1. Dimensional vs. Hierarchical Metrics
21.2. Default Metrics Collection
21.3. Metrics Collection: Spectator
21.3.1. Spectator Counter
21.3.2. Spectator Timer
21.3.3. Spectator Gauge
21.3.4. Spectator Distribution Summaries
21.4. Metrics Collection: Servo
21.4.1. Creating Servo Monitors
21.5. Metrics Backend: Atlas
21.5.1. Global tags
21.5.2. Using Atlas
21.6. Retrying Failed Requests
21.6.1. BackOff Policies
21.6.2. Configuration
21.6.3. Zuul
22. HTTP Clients
IV. Spring Cloud Stream
23. Introducing Spring Cloud Stream
24. Main Concepts
24.1. Application Model
24.1.1. Fat JAR
24.2. The Binder Abstraction
24.3. Persistent Publish-Subscribe Support
24.4. Consumer Groups
24.5. Consumer Types
24.5.1. Durability
24.6. Partitioning Support
25. Programming Model
25.1. Declaring and Binding Producers and Consumers
25.1.1. Triggering Binding Via @EnableBinding
25.1.2. @Input and @Output
Customizing Channel Names
Source, Sink, and Processor
25.1.3. Accessing Bound Channels
Injecting the Bound Interfaces
Injecting Channels Directly
25.1.4. Producing and Consuming Messages
Native Spring Integration Support
Spring Integration Error Channel Support
Message Channel Binders and Error Channels
Using @StreamListener for Automatic Content Type Handling
Using @StreamListener for dispatching messages to multiple methods
Using Polled Consumers
25.1.5. Reactive Programming Support
Reactor-based handlers
RxJava 1.x support
Reactive Sources
25.1.6. Aggregation
Configuring aggregate application
Configuring binding service properties for non self contained aggregate application
26. Binders
26.1. Producers and Consumers
26.2. Binder SPI
26.3. Binder Detection
26.3.1. Classpath Detection
26.4. Multiple Binders on the Classpath
26.5. Connecting to Multiple Systems
26.6. Binder configuration properties
27. Configuration Options
27.1. Spring Cloud Stream Properties
27.2. Binding Properties
27.2.1. Properties for Use of Spring Cloud Stream
27.2.2. Consumer properties
27.2.3. Producer Properties
27.3. Using dynamically bound destinations
28. Content Type and Transformation
28.1. MIME types
28.2. Channel contentType and Message Headers
28.3. ContentType handling for output channels
28.4. ContentType handling for input channels
28.5. Customizing message conversion
28.6. @StreamListener and Message Conversion
29. Schema evolution support
29.1. Apache Avro Message Converters
29.2. Converters with schema support
29.3. Schema Registry Support
29.4. Schema Registry Server
29.4.1. Schema Registry Server API
POST /
GET /{subject}/{format}/{version}
GET /{subject}/{format}
GET /schemas/{id}
DELETE /{subject}/{format}/{version}
DELETE /schemas/{id}
DELETE /{subject}
29.5. Schema Registry Client
29.5.1. Using Confluent’s Schema Registry
29.5.2. Schema Registry Client properties
29.6. Avro Schema Registry Client Message Converters
29.6.1. Avro Schema Registry Message Converter properties
29.7. Schema Registration and Resolution
29.7.1. Schema Registration Process (Serialization)
29.7.2. Schema Resolution Process (Deserialization)
30. Inter-Application Communication
30.1. Connecting Multiple Application Instances
30.2. Instance Index and Instance Count
30.3. Partitioning
30.3.1. Configuring Output Bindings for Partitioning
Configuring Input Bindings for Partitioning
31. Testing
31.1. Disabling the test binder autoconfiguration
32. Health Indicator
33. Metrics Emitter
34. Samples
35. Getting Started
35.1. Deploying Stream applications on CloudFoundry
V. Binder Implementations
36. Apache Kafka Binder
36.1. Usage
36.2. Apache Kafka Binder Overview
36.3. Configuration Options
36.3.1. Kafka Binder Properties
36.3.2. Kafka Consumer Properties
36.3.3. Kafka Producer Properties
36.3.4. Usage examples
Example: Setting autoCommitOffset false and relying on manual acking.
Example: security configuration
Example: Pausing and Resuming the Consumer
Using the binder with Apache Kafka 0.10
Excluding Kafka broker jar from the classpath of the binder based application
36.4. Kafka Streams Binding Capabilities of Spring Cloud Stream
36.4.1. Usage example of high level streams DSL
36.4.2. Message conversion in Spring Cloud Stream Kafka Streams applications
36.4.3. Support for branching in Kafka Streams API
36.4.4. Support for interactive queries
36.4.5. Kafka Streams properties
36.5. Error Channels
36.6. Kafka Metrics
36.7. Dead-Letter Topic Processing
36.8. Partitioning with the Kafka Binder
37. RabbitMQ Binder
37.1. Usage
37.2. RabbitMQ Binder Overview
37.3. Configuration Options
37.3.1. RabbitMQ Binder Properties
37.3.2. RabbitMQ Consumer Properties
37.3.3. Rabbit Producer Properties
37.4. Retry With the RabbitMQ Binder
37.4.1. Overview
37.4.2. Putting it All Together
37.5. Error Channels
37.6. Dead-Letter Queue Processing
37.6.1. Non-Partitioned Destinations
37.6.2. Partitioned Destinations
republishToDlq=false
republishToDlq=true
37.7. Partitioning with the RabbitMQ Binder
VI. Spring Cloud Bus
38. Quick Start
39. Addressing an Instance
40. Addressing all instances of a service
41. Service ID must be unique
42. Customizing the Message Broker
43. Tracing Bus Events
44. Broadcasting Your Own Events
44.1. Registering events in custom packages
VII. Spring Cloud Sleuth
45. Introduction
45.1. Terminology
45.2. Purpose
45.2.1. Distributed tracing with Zipkin
45.2.2. Visualizing errors
45.2.3. Distributed tracing with Brave
45.2.4. Live examples
45.2.5. Log correlation
JSON Logback with Logstash
45.2.6. Propagating Span Context
Baggage vs. Span Tags
45.3. Adding to the project
45.3.1. Only Sleuth (log correlation)
45.3.2. Sleuth with Zipkin via HTTP
45.3.3. Sleuth with Zipkin via RabbitMQ or Kafka
46. Additional resources
47. Features
47.1. Introduction to Brave
47.1.1. Tracing
47.1.2. Tracing
47.1.3. Local Tracing
47.1.4. Customizing spans
47.1.5. Implicitly looking up the current span
47.1.6. RPC tracing
One-Way tracing
48. Sampling
48.1. Declarative sampling
48.2. Custom sampling
48.3. Sampling in Spring Cloud Sleuth
49. Propagation
49.1. Propagating extra fields
49.1.1. Prefixed fields
49.1.2. Extracting a propagated context
49.1.3. Sharing span IDs between client and server
49.1.4. Implementing Propagation
50. Current Tracing Component
51. Current Span
51.1. Setting a span in scope manually
52. Instrumentation
53. Span lifecycle
53.1. Creating and finishing spans
53.2. Continuing spans
53.3. Creating spans with an explicit parent
54. Naming spans
54.1. @SpanName annotation
54.2. toString() method
55. Managing spans with annotations
55.1. Rationale
55.2. Creating new spans
55.3. Continuing spans
55.4. More advanced tag setting
55.4.1. Custom extractor
55.4.2. Resolving expressions for value
55.4.3. Using toString method
56. Customizations
56.1. Spring Integration
56.2. HTTP
56.3. TraceFilter
56.4. Custom service name
56.5. Customization of reported spans
56.6. Host locator
57. Sending spans to Zipkin
58. Zipkin Stream Span Consumer
59. Integrations
59.1. OpenTracing
59.2. Runnable and Callable
59.3. Hystrix
59.3.1. Custom Concurrency Strategy
59.3.2. Manual Command setting
59.4. RxJava
59.5. HTTP integration
59.5.1. HTTP Filter
59.5.2. HandlerInterceptor
59.5.3. Async Servlet support
59.5.4. WebFlux support
59.6. HTTP client integration
59.6.1. Synchronous Rest Template
59.6.2. Asynchronous Rest Template
Multiple Asynchronous Rest Templates
59.6.3. WebClient
59.6.4. Traverson
59.7. Feign
59.8. Asynchronous communication
59.8.1. @Async annotated methods
59.8.2. @Scheduled annotated methods
59.8.3. Executor, ExecutorService and ScheduledExecutorService
Customization of Executors
59.9. Messaging
59.10. Zuul
60. Running examples
VIII. Spring Cloud Consul
61. Install Consul
62. Consul Agent
63. Service Discovery with Consul
63.1. How to activate
63.2. Registering with Consul
63.3. HTTP Health Check
63.3.1. Metadata and Consul tags
63.3.2. Making the Consul Instance ID Unique
63.4. Looking up services
63.4.1. Using Ribbon
63.4.2. Using the DiscoveryClient
64. Distributed Configuration with Consul
64.1. How to activate
64.2. Customizing
64.3. Config Watch
64.4. YAML or Properties with Config
64.5. git2consul with Config
64.6. Fail Fast
65. Consul Retry
66. Spring Cloud Bus with Consul
66.1. How to activate
67. Circuit Breaker with Hystrix
68. Hystrix metrics aggregation with Turbine and Consul
IX. Spring Cloud Zookeeper
69. Install Zookeeper
70. Service Discovery with Zookeeper
70.1. How to activate
70.2. Registering with Zookeeper
70.3. Using the DiscoveryClient
71. Using Spring Cloud Zookeeper with Spring Cloud Netflix Components
71.1. Ribbon with Zookeeper
72. Spring Cloud Zookeeper and Service Registry
72.1. Instance Status
73. Zookeeper Dependencies
73.1. Using the Zookeeper Dependencies
73.2. How to activate Zookeeper Dependencies
73.3. Setting up Zookeeper Dependencies
73.3.1. Aliases
73.3.2. Path
73.3.3. Load balancer type
73.3.4. Content-Type template and version
73.3.5. Default headers
73.3.6. Obligatory dependencies
73.3.7. Stubs
73.4. Configuring Spring Cloud Zookeeper Dependencies
74. Spring Cloud Zookeeper Dependency Watcher
74.1. How to activate
74.2. Registering a listener
74.3. Presence Checker
75. Distributed Configuration with Zookeeper
75.1. How to activate
75.2. Customizing
75.3. ACLs
X. Spring Cloud Security
76. Quickstart
76.1. OAuth2 Single Sign On
76.2. OAuth2 Protected Resource
77. More Detail
77.1. Single Sign On
77.2. Token Relay
77.2.1. Client Token Relay
77.2.2. Client Token Relay in Zuul Proxy
77.2.3. Resource Server Token Relay
78. Configuring Authentication Downstream of a Zuul Proxy
XI. Spring Cloud for Cloud Foundry
79. Discovery
80. Single Sign On
XII. Spring Cloud Contract
81. Spring Cloud Contract
82. Spring Cloud Contract Verifier Introduction
82.1. Why a Contract Verifier?
82.1.1. Testing issues
82.2. Purposes
82.3. How It Works
82.3.1. Defining the contract
82.3.2. Client Side
82.3.3. Server Side
82.4. Step-by-step Guide to Consumer Driven Contracts (CDC)
82.4.1. Technical note
82.4.2. Consumer side (Loan Issuance)
82.4.3. Producer side (Fraud Detection server)
82.4.4. Consumer Side (Loan Issuance) Final Step
82.5. Dependencies
82.6. Additional Links
82.6.1. Spring Cloud Contract video
82.6.2. Readings
82.7. Samples
83. Spring Cloud Contract FAQ
83.1. Why use Spring Cloud Contract Verifier and not X ?
83.2. I don’t want to write a contract in Groovy!
83.3. What is this value(consumer(), producer()) ?
83.4. How to do Stubs versioning?
83.4.1. API Versioning
83.4.2. JAR versioning
83.4.3. Dev or prod stubs
83.5. Common repo with contracts
83.5.1. Repo structure
83.5.2. Workflow
83.5.3. Consumer
83.5.4. Producer
83.6. Can I have multiple base classes for tests?
83.7. How can I debug the request/response being sent by the generated tests client?
83.7.1. How can I debug the mapping/request/response being sent by WireMock?
83.7.2. How can I see what got registered in the HTTP server stub?
83.7.3. Can I reference the request from the response?
83.7.4. Can I reference text from file?
84. Spring Cloud Contract Verifier Setup
84.1. Gradle Project
84.1.1. Prerequisites
84.1.2. Add Gradle Plugin with Dependencies
84.1.3. Gradle and Rest Assured 2.0
84.1.4. Snapshot Versions for Gradle
84.1.5. Add stubs
84.1.6. Run the Plugin
84.1.7. Default Setup
84.1.8. Configure Plugin
84.1.9. Configuration Options
84.1.10. Single Base Class for All Tests
84.1.11. Different Base Classes for Contracts
84.1.12. Invoking Generated Tests
84.1.13. Spring Cloud Contract Verifier on the Consumer Side
84.2. Maven Project
84.2.1. Add maven plugin
84.2.2. Maven and Rest Assured 2.0
84.2.3. Snapshot versions for Maven
84.2.4. Add stubs
84.2.5. Run plugin
84.2.6. Configure plugin
84.2.7. Configuration Options
84.2.8. Single Base Class for All Tests
84.2.9. Different base classes for contracts
84.2.10. Invoking generated tests
84.2.11. Maven Plugin and STS
84.2.12. Spring Cloud Contract Verifier on the Consumer Side
84.3. Stubs and Transitive Dependencies
84.4. Scenarios
84.5. Docker Project
84.5.1. Short intro to Maven, JARs and Binary storage
84.5.2. How it works
Environment Variables
84.5.3. Example of usage
84.5.4. Server side (nodejs)
85. Spring Cloud Contract Verifier Messaging
85.1. Integrations
85.2. Manual Integration Testing
85.3. Publisher-Side Test Generation
85.3.1. Scenario 1: No Input Message
85.3.2. Scenario 2: Output Triggered by Input
85.3.3. Scenario 3: No Output Message
85.4. Consumer Stub Generation
86. Spring Cloud Contract Stub Runner
86.1. Snapshot versions
86.2. Publishing Stubs as JARs
86.3. Stub Runner Core
86.3.1. Retrieving stubs
Stub downloading
Classpath scanning
86.3.2. Running stubs
Limitations
Running using main app
HTTP Stubs
Viewing registered mappings
Messaging Stubs
86.4. Stub Runner JUnit Rule
86.4.1. Maven settings
86.4.2. Providing fixed ports
86.4.3. Fluent API
86.4.4. Stub Runner with Spring
86.5. Stub Runner Spring Cloud
86.5.1. Stubbing Service Discovery
Test profiles and service discovery
86.5.2. Additional Configuration
86.6. Stub Runner Boot Application
86.6.1. How to use it?
Stub Runner Server
Spring Cloud CLI
86.6.2. Endpoints
HTTP
Messaging
86.6.3. Example
86.6.4. Stub Runner Boot with Service Discovery
86.7. Stubs Per Consumer
86.8. Common
86.8.1. Common Properties for JUnit and Spring
86.8.2. Stub Runner Stubs IDs
86.9. Stub Runner Docker
86.9.1. How to use it
86.9.2. Example of client side usage in a non JVM project
87. Stub Runner for Messaging
87.1. Stub triggering
87.1.1. Trigger by Label
87.1.2. Trigger by Group and Artifact Ids
87.1.3. Trigger by Artifact Ids
87.1.4. Trigger All Messages
87.2. Stub Runner Integration
87.2.1. Adding the Runner to the Project
87.2.2. Disabling the functionality
Scenario 1 (no input message)
Scenario 2 (output triggered by input)
Scenario 3 (input with no output)
87.3. Stub Runner Stream
87.3.1. Adding the Runner to the Project
87.3.2. Disabling the functionality
Scenario 1 (no input message)
Scenario 2 (output triggered by input)
Scenario 3 (input with no output)
87.4. Stub Runner Spring AMQP
87.4.1. Adding the Runner to the Project
Triggering the message
Spring AMQP Test Configuration
88. Contract DSL
88.1. Limitations
88.2. Common Top-Level elements
88.2.1. Description
88.2.2. Name
88.2.3. Ignoring Contracts
88.2.4. Passing Values from Files
88.2.5. HTTP Top-Level Elements
88.3. Request
88.4. Response
88.5. Dynamic properties
88.5.1. Dynamic properties inside the body
88.5.2. Regular expressions
88.5.3. Passing Optional Parameters
88.5.4. Executing Custom Methods on the Server Side
88.5.5. Referencing the Request from the Response
88.5.6. Registering Your Own WireMock Extension
88.5.7. Dynamic Properties in the Matchers Sections
88.6. JAX-RS Support
88.7. Async Support
88.8. Working with Context Paths
88.9. Messaging Top-Level Elements
88.9.1. Output Triggered by a Method
88.9.2. Output Triggered by a Message
88.9.3. Consumer/Producer
88.9.4. Common
88.10. Multiple Contracts in One File
89. Customization
89.1. Extending the DSL
89.1.1. Common JAR
89.1.2. Adding the Dependency to the Project
89.1.3. Test the Dependency in the Project’s Dependencies
89.1.4. Test a Dependency in the Plugin’s Dependencies
89.1.5. Referencing classes in DSLs
90. Using the Pluggable Architecture
90.1. Custom Contract Converter
90.1.1. Pact Converter
90.1.2. Pact Contract
90.1.3. Pact for Producers
90.1.4. Pact for Consumers
90.2. Using the Custom Test Generator
90.3. Using the Custom Stub Generator
90.4. Using the Custom Stub Runner
90.5. Using the Custom Stub Downloader
91. Spring Cloud Contract WireMock
91.1. Registering Stubs Automatically
91.2. Using Files to Specify the Stub Bodies
91.3. Alternative: Using JUnit Rules
91.4. Relaxed SSL Validation for Rest Template
91.5. WireMock and Spring MVC Mocks
91.6. Customization of WireMock configuration
91.7. Generating Stubs using REST Docs
91.8. Generating Contracts by Using REST Docs
92. Migrations
92.1. 1.0.x → 1.1.x
92.1.1. New structure of generated stubs
92.2. 1.1.x → 1.2.x
92.2.1. Custom HttpServerStub
92.2.2. New packages for generated tests
92.2.3. New Methods in TemplateProcessor
92.2.4. RestAssured 3.0
92.3. 1.2.x → 2.0.x
92.3.1. No Camel support
93. Links
XIII. Spring Cloud Vault
94. Quick Start
95. Client Side Usage
95.1. Authentication
96. Authentication methods
96.1. Token authentication
96.2. AppId authentication
96.2.1. Custom UserId
96.3. AppRole authentication
96.4. AWS-EC2 authentication
96.5. AWS-IAM authentication
96.6. TLS certificate authentication
96.7. Cubbyhole authentication
96.8. Kubernetes authentication
97. Secret Backends
97.1. Generic Backend
97.2. Consul
97.3. RabbitMQ
97.4. AWS
98. Database backends
98.1. Database
98.2. Apache Cassandra
98.3. MongoDB
98.4. MySQL
98.5. PostgreSQL
99. Configure PropertySourceLocator behavior
100. Service Registry Configuration
101. Vault Client Fail Fast
102. Vault Client SSL configuration
103. Lease lifecycle management (renewal and revocation)
XIV. Spring Cloud Gateway
104. How to Include Spring Cloud Gateway
105. Glossary
106. How It Works
107. Route Predicate Factories
107.1. After Route Predicate Factory
107.2. Before Route Predicate Factory
107.3. Between Route Predicate Factory
107.4. Cookie Route Predicate Factory
107.5. Header Route Predicate Factory
107.6. Host Route Predicate Factory
107.7. Method Route Predicate Factory
107.8. Path Route Predicate Factory
107.9. Query Route Predicate Factory
107.10. RemoteAddr Route Predicate Factory
108. GatewayFilter Factories
108.1. AddRequestHeader GatewayFilter Factory
108.2. AddRequestParameter GatewayFilter Factory
108.3. AddResponseHeader GatewayFilter Factory
108.4. Hystrix GatewayFilter Factory
108.5. PrefixPath GatewayFilter Factory
108.6. PreserveHostHeader GatewayFilter Factory
108.7. RequestRateLimiter GatewayFilter Factory
108.8. RedirectTo GatewayFilter Factory
108.9. RemoveNonProxyHeaders GatewayFilter Factory
108.10. RemoveRequestHeader GatewayFilter Factory
108.11. RemoveResponseHeader GatewayFilter Factory
108.12. RewritePath GatewayFilter Factory
108.13. SaveSession GatewayFilter Factory
108.14. SecureHeaders GatewayFilter Factory
108.15. SetPath GatewayFilter Factory
108.16. SetResponseHeader GatewayFilter Factory
108.17. SetStatus GatewayFilter Factory
109. Global Filters
109.1. Combined Global Filter and GatewayFilter Ordering
109.2. Forward Routing Filter
109.3. LoadBalancerClient Filter
109.4. Netty Routing Filter
109.5. Netty Write Response Filter
109.6. RouteToRequestUrl Filter
109.7. Websocket Routing Filter
110. Configuration
110.1. Fluent Java Routes API
110.2. DiscoveryClient Route Definition Locator
111. Actuator API
112. Developer Guide
112.1. Writing Custom Route Predicate Factories
112.2. Writing Custom GatewayFilter Factories
112.3. Writing Custom Global Filters
112.4. Writing Custom Route Locators and Writers
113. Building a Simple Gateway Using Spring MVC
XV. Appendix: Compendium of Configuration Properties
\ No newline at end of file diff --git a/Finchley.M6/multi/multi_vault-lease-renewal.html b/Finchley.M6/multi/multi_vault-lease-renewal.html index fa1e4a11..f51f9b6b 100644 --- a/Finchley.M6/multi/multi_vault-lease-renewal.html +++ b/Finchley.M6/multi/multi_vault-lease-renewal.html @@ -1,6 +1,6 @@ - 103. Lease lifecycle management (renewal and revocation)

103. Lease lifecycle management (renewal and revocation)

With every secret, Vault creates a lease: + 103. Lease lifecycle management (renewal and revocation)

103. Lease lifecycle management (renewal and revocation)

With every secret, Vault creates a lease: metadata containing information such as a time duration, renewability, and more.

Vault promises that the data will be valid for the given duration, or Time To Live (TTL). Once the lease is expired, Vault can @@ -19,4 +19,4 @@ to false. This is not recommended as leases can exp Spring Cloud Vault cannot longer access Vault or services using generated credentials and valid credentials remain active after application shutdown.

spring.cloud.vault:
-    config.lifecycle.enabled: true

See also: Vault Documentation: Lease, Renew, and Revoke

\ No newline at end of file + config.lifecycle.enabled: true

See also: Vault Documentation: Lease, Renew, and Revoke

\ No newline at end of file diff --git a/Finchley.M6/single/spring-cloud.html b/Finchley.M6/single/spring-cloud.html index 34c01b9b..a0b674ec 100644 --- a/Finchley.M6/single/spring-cloud.html +++ b/Finchley.M6/single/spring-cloud.html @@ -1,6 +1,6 @@ - Spring Cloud

Spring Cloud


Table of Contents

1. Features
I. Cloud Native Applications
2. Spring Cloud Context: Application Context Services
2.1. The Bootstrap Application Context
2.2. Application Context Hierarchies
2.3. Changing the Location of Bootstrap Properties
2.4. Overriding the Values of Remote Properties
2.5. Customizing the Bootstrap Configuration
2.6. Customizing the Bootstrap Property Sources
2.7. Environment Changes
2.8. Refresh Scope
2.9. Encryption and Decryption
2.10. Endpoints
3. Spring Cloud Commons: Common Abstractions
3.1. @EnableDiscoveryClient
3.1.1. Health Indicator
3.2. ServiceRegistry
3.2.1. ServiceRegistry Auto-Registration
3.2.2. Service Registry Actuator Endpoint
3.3. Spring RestTemplate as a Load Balancer Client
3.4. Spring WebClient as a Load Balancer Client
3.4.1. Retrying Failed Requests
3.5. Multiple RestTemplate objects
3.6. Spring WebFlux WebClient as a Load Balancer Client
3.7. Ignore Network Interfaces
3.8. HTTP Client Factories
3.9. Enabled Features
3.9.1. Feature types
3.9.2. Declaring features
II. Spring Cloud Config
4. Quick Start
4.1. Client Side Usage
5. Spring Cloud Config Server
5.1. Environment Repository
5.1.1. Git Backend
Placeholders in Git URI
Pattern Matching and Multiple Repositories
Authentication
Authentication with AWS CodeCommit
Git SSH configuration using properties
Placeholders in Git Search Paths
Force pull in Git Repositories
5.1.2. Version Control Backend Filesystem Use
5.1.3. File System Backend
5.1.4. Vault Backend
Multiple Properties Sources
5.1.5. Sharing Configuration With All Applications
File Based Repositories
Vault Server
5.1.6. JDBC Backend
5.1.7. Composite Environment Repositories
Custom Composite Environment Repositories
5.1.8. Property Overrides
5.2. Health Indicator
5.3. Security
5.4. Encryption and Decryption
5.5. Key Management
5.6. Creating a Key Store for Testing
5.7. Using Multiple Keys and Key Rotation
5.8. Serving Encrypted Properties
6. Serving Alternative Formats
7. Serving Plain Text
8. Embedding the Config Server
9. Push Notifications and Spring Cloud Bus
10. Spring Cloud Config Client
10.1. Config First Bootstrap
10.2. Discovery First Bootstrap
10.3. Config Client Fail Fast
10.4. Config Client Retry
10.5. Locating Remote Configuration Resources
10.6. Security
10.6.1. Health Indicator
10.6.2. Providing A Custom RestTemplate
10.6.3. Vault
10.7. Vault
10.7.1. Nested Keys In Vault
III. Spring Cloud Netflix
11. Service Discovery: Eureka Clients
11.1. How to Include Eureka Client
11.2. Registering with Eureka
11.3. Authenticating with the Eureka Server
11.4. Status Page and Health Indicator
11.5. Registering a Secure Application
11.6. Eureka’s Health Checks
11.7. Eureka Metadata for Instances and Clients
11.7.1. Using Eureka on Cloudfoundry
11.7.2. Using Eureka on AWS
11.7.3. Changing the Eureka Instance ID
11.8. Using the EurekaClient
11.8.1. EurekaClient without Jersey
11.9. Alternatives to the native Netflix EurekaClient
11.10. Why is it so Slow to Register a Service?
11.11. Zones
12. Service Discovery: Eureka Server
12.1. How to Include Eureka Server
12.2. How to Run a Eureka Server
12.3. High Availability, Zones and Regions
12.4. Standalone Mode
12.5. Peer Awareness
12.6. Prefer IP Address
13. Circuit Breaker: Hystrix Clients
13.1. How to Include Hystrix
13.2. Propagating the Security Context or using Spring Scopes
13.3. Health Indicator
13.4. Hystrix Metrics Stream
14. Circuit Breaker: Hystrix Dashboard
15. Hystrix Timeouts And Ribbon Clients
15.1. How to Include Hystrix Dashboard
15.2. Turbine
15.3. Turbine Stream
16. Client Side Load Balancer: Ribbon
16.1. How to Include Ribbon
16.2. Customizing the Ribbon Client
16.3. Customizing default for all Ribbon Clients
16.4. Customizing the Ribbon Client using properties
16.5. Using Ribbon with Eureka
16.6. Example: How to Use Ribbon Without Eureka
16.7. Example: Disable Eureka use in Ribbon
16.8. Using the Ribbon API Directly
16.9. Caching of Ribbon Configuration
16.10. How to Configure Hystrix thread pools
16.11. How to Provide a Key to Ribbon’s IRule
17. Declarative REST Client: Feign
17.1. How to Include Feign
17.2. Overriding Feign Defaults
17.3. Creating Feign Clients Manually
17.4. Feign Hystrix Support
17.5. Feign Hystrix Fallbacks
17.6. Feign and @Primary
17.7. Feign Inheritance Support
17.8. Feign request/response compression
17.9. Feign logging
18. External Configuration: Archaius
19. Router and Filter: Zuul
19.1. How to Include Zuul
19.2. Embedded Zuul Reverse Proxy
19.3. Zuul Http Client
19.4. Cookies and Sensitive Headers
19.5. Ignored Headers
19.6. Management Endpoints
19.6.1. Routes Endpoint
19.6.2. Filters Endpoint
19.7. Strangulation Patterns and Local Forwards
19.8. Uploading Files through Zuul
19.9. Query String Encoding
19.10. Plain Embedded Zuul
19.11. Disable Zuul Filters
19.12. Providing Hystrix Fallbacks For Routes
19.13. Zuul Timeouts
19.14. Rewriting Location header
19.15. Zuul Developer Guide
19.15.1. The Zuul Servlet
19.15.2. Zuul RequestContext
19.15.3. @EnableZuulProxy vs. @EnableZuulServer
19.15.4. @EnableZuulServer Filters
19.15.5. @EnableZuulProxy Filters
19.15.6. Custom Zuul Filter examples
19.15.7. How to Write a Pre Filter
19.15.8. How to Write a Route Filter
19.15.9. How to Write a Post Filter
19.15.10. How Zuul Errors Work
19.15.11. Zuul Eager Application Context Loading
20. Polyglot support with Sidecar
21. Metrics: Spectator, Servo, and Atlas
21.1. Dimensional vs. Hierarchical Metrics
21.2. Default Metrics Collection
21.3. Metrics Collection: Spectator
21.3.1. Spectator Counter
21.3.2. Spectator Timer
21.3.3. Spectator Gauge
21.3.4. Spectator Distribution Summaries
21.4. Metrics Collection: Servo
21.4.1. Creating Servo Monitors
21.5. Metrics Backend: Atlas
21.5.1. Global tags
21.5.2. Using Atlas
21.6. Retrying Failed Requests
21.6.1. BackOff Policies
21.6.2. Configuration
21.6.3. Zuul
22. HTTP Clients
IV. Spring Cloud Stream
23. Introducing Spring Cloud Stream
24. Main Concepts
24.1. Application Model
24.1.1. Fat JAR
24.2. The Binder Abstraction
24.3. Persistent Publish-Subscribe Support
24.4. Consumer Groups
24.5. Consumer Types
24.5.1. Durability
24.6. Partitioning Support
25. Programming Model
25.1. Declaring and Binding Producers and Consumers
25.1.1. Triggering Binding Via @EnableBinding
25.1.2. @Input and @Output
Customizing Channel Names
Source, Sink, and Processor
25.1.3. Accessing Bound Channels
Injecting the Bound Interfaces
Injecting Channels Directly
25.1.4. Producing and Consuming Messages
Native Spring Integration Support
Spring Integration Error Channel Support
Message Channel Binders and Error Channels
Using @StreamListener for Automatic Content Type Handling
Using @StreamListener for dispatching messages to multiple methods
Using Polled Consumers
25.1.5. Reactive Programming Support
Reactor-based handlers
RxJava 1.x support
Reactive Sources
25.1.6. Aggregation
Configuring aggregate application
Configuring binding service properties for non self contained aggregate application
26. Binders
26.1. Producers and Consumers
26.2. Binder SPI
26.3. Binder Detection
26.3.1. Classpath Detection
26.4. Multiple Binders on the Classpath
26.5. Connecting to Multiple Systems
26.6. Binder configuration properties
27. Configuration Options
27.1. Spring Cloud Stream Properties
27.2. Binding Properties
27.2.1. Properties for Use of Spring Cloud Stream
27.2.2. Consumer properties
27.2.3. Producer Properties
27.3. Using dynamically bound destinations
28. Content Type and Transformation
28.1. MIME types
28.2. Channel contentType and Message Headers
28.3. ContentType handling for output channels
28.4. ContentType handling for input channels
28.5. Customizing message conversion
28.6. @StreamListener and Message Conversion
29. Schema evolution support
29.1. Apache Avro Message Converters
29.2. Converters with schema support
29.3. Schema Registry Support
29.4. Schema Registry Server
29.4.1. Schema Registry Server API
POST /
GET /{subject}/{format}/{version}
GET /{subject}/{format}
GET /schemas/{id}
DELETE /{subject}/{format}/{version}
DELETE /schemas/{id}
DELETE /{subject}
29.5. Schema Registry Client
29.5.1. Using Confluent’s Schema Registry
29.5.2. Schema Registry Client properties
29.6. Avro Schema Registry Client Message Converters
29.6.1. Avro Schema Registry Message Converter properties
29.7. Schema Registration and Resolution
29.7.1. Schema Registration Process (Serialization)
29.7.2. Schema Resolution Process (Deserialization)
30. Inter-Application Communication
30.1. Connecting Multiple Application Instances
30.2. Instance Index and Instance Count
30.3. Partitioning
30.3.1. Configuring Output Bindings for Partitioning
Configuring Input Bindings for Partitioning
31. Testing
31.1. Disabling the test binder autoconfiguration
32. Health Indicator
33. Metrics Emitter
34. Samples
35. Getting Started
35.1. Deploying Stream applications on CloudFoundry
V. Binder Implementations
36. Apache Kafka Binder
36.1. Usage
36.2. Apache Kafka Binder Overview
36.3. Configuration Options
36.3.1. Kafka Binder Properties
36.3.2. Kafka Consumer Properties
36.3.3. Kafka Producer Properties
36.3.4. Usage examples
Example: Setting autoCommitOffset false and relying on manual acking.
Example: security configuration
Example: Pausing and Resuming the Consumer
Using the binder with Apache Kafka 0.10
Excluding Kafka broker jar from the classpath of the binder based application
36.4. Kafka Streams Binding Capabilities of Spring Cloud Stream
36.4.1. Usage example of high level streams DSL
36.4.2. Message conversion in Spring Cloud Stream Kafka Streams applications
36.4.3. Support for branching in Kafka Streams API
36.4.4. Support for interactive queries
36.4.5. Kafka Streams properties
36.5. Error Channels
36.6. Kafka Metrics
36.7. Dead-Letter Topic Processing
36.8. Partitioning with the Kafka Binder
37. RabbitMQ Binder
37.1. Usage
37.2. RabbitMQ Binder Overview
37.3. Configuration Options
37.3.1. RabbitMQ Binder Properties
37.3.2. RabbitMQ Consumer Properties
37.3.3. Rabbit Producer Properties
37.4. Retry With the RabbitMQ Binder
37.4.1. Overview
37.4.2. Putting it All Together
37.5. Error Channels
37.6. Dead-Letter Queue Processing
37.6.1. Non-Partitioned Destinations
37.6.2. Partitioned Destinations
republishToDlq=false
republishToDlq=true
37.7. Partitioning with the RabbitMQ Binder
VI. Spring Cloud Bus
38. Quick Start
39. Addressing an Instance
40. Addressing all instances of a service
41. Service ID must be unique
42. Customizing the Message Broker
43. Tracing Bus Events
44. Broadcasting Your Own Events
44.1. Registering events in custom packages
VII. Spring Cloud Sleuth
45. Introduction
45.1. Terminology
45.2. Purpose
45.2.1. Distributed tracing with Zipkin
45.2.2. Visualizing errors
45.2.3. Distributed tracing with Brave
45.2.4. Live examples
45.2.5. Log correlation
JSON Logback with Logstash
45.2.6. Propagating Span Context
Baggage vs. Span Tags
45.3. Adding to the project
45.3.1. Only Sleuth (log correlation)
45.3.2. Sleuth with Zipkin via HTTP
45.3.3. Sleuth with Zipkin via RabbitMQ or Kafka
46. Additional resources
47. Features
47.1. Introduction to Brave
47.1.1. Tracing
47.1.2. Tracing
47.1.3. Local Tracing
47.1.4. Customizing spans
47.1.5. Implicitly looking up the current span
47.1.6. RPC tracing
One-Way tracing
48. Sampling
48.1. Declarative sampling
48.2. Custom sampling
48.3. Sampling in Spring Cloud Sleuth
49. Propagation
49.1. Propagating extra fields
49.1.1. Prefixed fields
49.1.2. Extracting a propagated context
49.1.3. Sharing span IDs between client and server
49.1.4. Implementing Propagation
50. Current Tracing Component
51. Current Span
51.1. Setting a span in scope manually
52. Instrumentation
53. Span lifecycle
53.1. Creating and finishing spans
53.2. Continuing spans
53.3. Creating spans with an explicit parent
54. Naming spans
54.1. @SpanName annotation
54.2. toString() method
55. Managing spans with annotations
55.1. Rationale
55.2. Creating new spans
55.3. Continuing spans
55.4. More advanced tag setting
55.4.1. Custom extractor
55.4.2. Resolving expressions for value
55.4.3. Using toString method
56. Customizations
56.1. Spring Integration
56.2. HTTP
56.3. TraceFilter
56.4. Custom service name
56.5. Customization of reported spans
56.6. Host locator
57. Sending spans to Zipkin
58. Zipkin Stream Span Consumer
59. Integrations
59.1. OpenTracing
59.2. Runnable and Callable
59.3. Hystrix
59.3.1. Custom Concurrency Strategy
59.3.2. Manual Command setting
59.4. RxJava
59.5. HTTP integration
59.5.1. HTTP Filter
59.5.2. HandlerInterceptor
59.5.3. Async Servlet support
59.5.4. WebFlux support
59.6. HTTP client integration
59.6.1. Synchronous Rest Template
59.6.2. Asynchronous Rest Template
Multiple Asynchronous Rest Templates
59.6.3. WebClient
59.6.4. Traverson
59.7. Feign
59.8. Asynchronous communication
59.8.1. @Async annotated methods
59.8.2. @Scheduled annotated methods
59.8.3. Executor, ExecutorService and ScheduledExecutorService
Customization of Executors
59.9. Messaging
59.10. Zuul
60. Running examples
VIII. Spring Cloud Consul
61. Install Consul
62. Consul Agent
63. Service Discovery with Consul
63.1. How to activate
63.2. Registering with Consul
63.3. HTTP Health Check
63.3.1. Metadata and Consul tags
63.3.2. Making the Consul Instance ID Unique
63.4. Looking up services
63.4.1. Using Ribbon
63.4.2. Using the DiscoveryClient
64. Distributed Configuration with Consul
64.1. How to activate
64.2. Customizing
64.3. Config Watch
64.4. YAML or Properties with Config
64.5. git2consul with Config
64.6. Fail Fast
65. Consul Retry
66. Spring Cloud Bus with Consul
66.1. How to activate
67. Circuit Breaker with Hystrix
68. Hystrix metrics aggregation with Turbine and Consul
IX. Spring Cloud Zookeeper
69. Install Zookeeper
70. Service Discovery with Zookeeper
70.1. How to activate
70.2. Registering with Zookeeper
70.3. Using the DiscoveryClient
71. Using Spring Cloud Zookeeper with Spring Cloud Netflix Components
71.1. Ribbon with Zookeeper
72. Spring Cloud Zookeeper and Service Registry
72.1. Instance Status
73. Zookeeper Dependencies
73.1. Using the Zookeeper Dependencies
73.2. How to activate Zookeeper Dependencies
73.3. Setting up Zookeeper Dependencies
73.3.1. Aliases
73.3.2. Path
73.3.3. Load balancer type
73.3.4. Content-Type template and version
73.3.5. Default headers
73.3.6. Obligatory dependencies
73.3.7. Stubs
73.4. Configuring Spring Cloud Zookeeper Dependencies
74. Spring Cloud Zookeeper Dependency Watcher
74.1. How to activate
74.2. Registering a listener
74.3. Presence Checker
75. Distributed Configuration with Zookeeper
75.1. How to activate
75.2. Customizing
75.3. ACLs
X. Spring Cloud Security
76. Quickstart
76.1. OAuth2 Single Sign On
76.2. OAuth2 Protected Resource
77. More Detail
77.1. Single Sign On
77.2. Token Relay
77.2.1. Client Token Relay
77.2.2. Client Token Relay in Zuul Proxy
77.2.3. Resource Server Token Relay
78. Configuring Authentication Downstream of a Zuul Proxy
XI. Spring Cloud for Cloud Foundry
79. Discovery
80. Single Sign On
XII. Spring Cloud Contract
81. Spring Cloud Contract
82. Spring Cloud Contract Verifier Introduction
82.1. Why a Contract Verifier?
82.1.1. Testing issues
82.2. Purposes
82.3. How It Works
82.3.1. Defining the contract
82.3.2. Client Side
82.3.3. Server Side
82.4. Step-by-step Guide to Consumer Driven Contracts (CDC)
82.4.1. Technical note
82.4.2. Consumer side (Loan Issuance)
82.4.3. Producer side (Fraud Detection server)
82.4.4. Consumer Side (Loan Issuance) Final Step
82.5. Dependencies
82.6. Additional Links
82.6.1. Spring Cloud Contract video
82.6.2. Readings
82.7. Samples
83. Spring Cloud Contract FAQ
83.1. Why use Spring Cloud Contract Verifier and not X ?
83.2. I don’t want to write a contract in Groovy!
83.3. What is this value(consumer(), producer()) ?
83.4. How to do Stubs versioning?
83.4.1. API Versioning
83.4.2. JAR versioning
83.4.3. Dev or prod stubs
83.5. Common repo with contracts
83.5.1. Repo structure
83.5.2. Workflow
83.5.3. Consumer
83.5.4. Producer
83.6. Can I have multiple base classes for tests?
83.7. How can I debug the request/response being sent by the generated tests client?
83.7.1. How can I debug the mapping/request/response being sent by WireMock?
83.7.2. How can I see what got registered in the HTTP server stub?
83.7.3. Can I reference the request from the response?
83.7.4. Can I reference text from file?
84. Spring Cloud Contract Verifier Setup
84.1. Gradle Project
84.1.1. Prerequisites
84.1.2. Add Gradle Plugin with Dependencies
84.1.3. Gradle and Rest Assured 2.0
84.1.4. Snapshot Versions for Gradle
84.1.5. Add stubs
84.1.6. Run the Plugin
84.1.7. Default Setup
84.1.8. Configure Plugin
84.1.9. Configuration Options
84.1.10. Single Base Class for All Tests
84.1.11. Different Base Classes for Contracts
84.1.12. Invoking Generated Tests
84.1.13. Spring Cloud Contract Verifier on the Consumer Side
84.2. Maven Project
84.2.1. Add maven plugin
84.2.2. Maven and Rest Assured 2.0
84.2.3. Snapshot versions for Maven
84.2.4. Add stubs
84.2.5. Run plugin
84.2.6. Configure plugin
84.2.7. Configuration Options
84.2.8. Single Base Class for All Tests
84.2.9. Different base classes for contracts
84.2.10. Invoking generated tests
84.2.11. Maven Plugin and STS
84.2.12. Spring Cloud Contract Verifier on the Consumer Side
84.3. Stubs and Transitive Dependencies
84.4. Scenarios
84.5. Docker Project
84.5.1. Short intro to Maven, JARs and Binary storage
84.5.2. How it works
Environment Variables
84.5.3. Example of usage
84.5.4. Server side (nodejs)
85. Spring Cloud Contract Verifier Messaging
85.1. Integrations
85.2. Manual Integration Testing
85.3. Publisher-Side Test Generation
85.3.1. Scenario 1: No Input Message
85.3.2. Scenario 2: Output Triggered by Input
85.3.3. Scenario 3: No Output Message
85.4. Consumer Stub Generation
86. Spring Cloud Contract Stub Runner
86.1. Snapshot versions
86.2. Publishing Stubs as JARs
86.3. Stub Runner Core
86.3.1. Retrieving stubs
Stub downloading
Classpath scanning
86.3.2. Running stubs
Limitations
Running using main app
HTTP Stubs
Viewing registered mappings
Messaging Stubs
86.4. Stub Runner JUnit Rule
86.4.1. Maven settings
86.4.2. Providing fixed ports
86.4.3. Fluent API
86.4.4. Stub Runner with Spring
86.5. Stub Runner Spring Cloud
86.5.1. Stubbing Service Discovery
Test profiles and service discovery
86.5.2. Additional Configuration
86.6. Stub Runner Boot Application
86.6.1. How to use it?
Stub Runner Server
Spring Cloud CLI
86.6.2. Endpoints
HTTP
Messaging
86.6.3. Example
86.6.4. Stub Runner Boot with Service Discovery
86.7. Stubs Per Consumer
86.8. Common
86.8.1. Common Properties for JUnit and Spring
86.8.2. Stub Runner Stubs IDs
86.9. Stub Runner Docker
86.9.1. How to use it
86.9.2. Example of client side usage in a non JVM project
87. Stub Runner for Messaging
87.1. Stub triggering
87.1.1. Trigger by Label
87.1.2. Trigger by Group and Artifact Ids
87.1.3. Trigger by Artifact Ids
87.1.4. Trigger All Messages
87.2. Stub Runner Integration
87.2.1. Adding the Runner to the Project
87.2.2. Disabling the functionality
Scenario 1 (no input message)
Scenario 2 (output triggered by input)
Scenario 3 (input with no output)
87.3. Stub Runner Stream
87.3.1. Adding the Runner to the Project
87.3.2. Disabling the functionality
Scenario 1 (no input message)
Scenario 2 (output triggered by input)
Scenario 3 (input with no output)
87.4. Stub Runner Spring AMQP
87.4.1. Adding the Runner to the Project
Triggering the message
Spring AMQP Test Configuration
88. Contract DSL
88.1. Limitations
88.2. Common Top-Level elements
88.2.1. Description
88.2.2. Name
88.2.3. Ignoring Contracts
88.2.4. Passing Values from Files
88.2.5. HTTP Top-Level Elements
88.3. Request
88.4. Response
88.5. Dynamic properties
88.5.1. Dynamic properties inside the body
88.5.2. Regular expressions
88.5.3. Passing Optional Parameters
88.5.4. Executing Custom Methods on the Server Side
88.5.5. Referencing the Request from the Response
88.5.6. Registering Your Own WireMock Extension
88.5.7. Dynamic Properties in the Matchers Sections
88.6. JAX-RS Support
88.7. Async Support
88.8. Working with Context Paths
88.9. Messaging Top-Level Elements
88.9.1. Output Triggered by a Method
88.9.2. Output Triggered by a Message
88.9.3. Consumer/Producer
88.9.4. Common
88.10. Multiple Contracts in One File
89. Customization
89.1. Extending the DSL
89.1.1. Common JAR
89.1.2. Adding the Dependency to the Project
89.1.3. Test the Dependency in the Project’s Dependencies
89.1.4. Test a Dependency in the Plugin’s Dependencies
89.1.5. Referencing classes in DSLs
90. Using the Pluggable Architecture
90.1. Custom Contract Converter
90.1.1. Pact Converter
90.1.2. Pact Contract
90.1.3. Pact for Producers
90.1.4. Pact for Consumers
90.2. Using the Custom Test Generator
90.3. Using the Custom Stub Generator
90.4. Using the Custom Stub Runner
90.5. Using the Custom Stub Downloader
91. Spring Cloud Contract WireMock
91.1. Registering Stubs Automatically
91.2. Using Files to Specify the Stub Bodies
91.3. Alternative: Using JUnit Rules
91.4. Relaxed SSL Validation for Rest Template
91.5. WireMock and Spring MVC Mocks
91.6. Customization of WireMock configuration
91.7. Generating Stubs using REST Docs
91.8. Generating Contracts by Using REST Docs
92. Migrations
92.1. 1.0.x → 1.1.x
92.1.1. New structure of generated stubs
92.2. 1.1.x → 1.2.x
92.2.1. Custom HttpServerStub
92.2.2. New packages for generated tests
92.2.3. New Methods in TemplateProcessor
92.2.4. RestAssured 3.0
92.3. 1.2.x → 2.0.x
92.3.1. No Camel support
93. Links
XIII. Spring Cloud Vault
94. Quick Start
95. Client Side Usage
95.1. Authentication
96. Authentication methods
96.1. Token authentication
96.2. AppId authentication
96.2.1. Custom UserId
96.3. AppRole authentication
96.4. AWS-EC2 authentication
96.5. AWS-IAM authentication
96.6. TLS certificate authentication
96.7. Cubbyhole authentication
96.8. Kubernetes authentication
97. Secret Backends
97.1. Generic Backend
97.2. Consul
97.3. RabbitMQ
97.4. AWS
98. Database backends
98.1. Database
98.2. Apache Cassandra
98.3. MongoDB
98.4. MySQL
98.5. PostgreSQL
99. Configure PropertySourceLocator behavior
100. Service Registry Configuration
101. Vault Client Fail Fast
102. Vault Client SSL configuration
103. Lease lifecycle management (renewal and revocation)
XIV. Appendix: Compendium of Configuration Properties

Spring Cloud provides tools for developers to quickly build some of + Spring Cloud

Spring Cloud


Table of Contents

1. Features
I. Cloud Native Applications
2. Spring Cloud Context: Application Context Services
2.1. The Bootstrap Application Context
2.2. Application Context Hierarchies
2.3. Changing the Location of Bootstrap Properties
2.4. Overriding the Values of Remote Properties
2.5. Customizing the Bootstrap Configuration
2.6. Customizing the Bootstrap Property Sources
2.7. Environment Changes
2.8. Refresh Scope
2.9. Encryption and Decryption
2.10. Endpoints
3. Spring Cloud Commons: Common Abstractions
3.1. @EnableDiscoveryClient
3.1.1. Health Indicator
3.2. ServiceRegistry
3.2.1. ServiceRegistry Auto-Registration
3.2.2. Service Registry Actuator Endpoint
3.3. Spring RestTemplate as a Load Balancer Client
3.4. Spring WebClient as a Load Balancer Client
3.4.1. Retrying Failed Requests
3.5. Multiple RestTemplate objects
3.6. Spring WebFlux WebClient as a Load Balancer Client
3.7. Ignore Network Interfaces
3.8. HTTP Client Factories
3.9. Enabled Features
3.9.1. Feature types
3.9.2. Declaring features
II. Spring Cloud Config
4. Quick Start
4.1. Client Side Usage
5. Spring Cloud Config Server
5.1. Environment Repository
5.1.1. Git Backend
Placeholders in Git URI
Pattern Matching and Multiple Repositories
Authentication
Authentication with AWS CodeCommit
Git SSH configuration using properties
Placeholders in Git Search Paths
Force pull in Git Repositories
5.1.2. Version Control Backend Filesystem Use
5.1.3. File System Backend
5.1.4. Vault Backend
Multiple Properties Sources
5.1.5. Sharing Configuration With All Applications
File Based Repositories
Vault Server
5.1.6. JDBC Backend
5.1.7. Composite Environment Repositories
Custom Composite Environment Repositories
5.1.8. Property Overrides
5.2. Health Indicator
5.3. Security
5.4. Encryption and Decryption
5.5. Key Management
5.6. Creating a Key Store for Testing
5.7. Using Multiple Keys and Key Rotation
5.8. Serving Encrypted Properties
6. Serving Alternative Formats
7. Serving Plain Text
8. Embedding the Config Server
9. Push Notifications and Spring Cloud Bus
10. Spring Cloud Config Client
10.1. Config First Bootstrap
10.2. Discovery First Bootstrap
10.3. Config Client Fail Fast
10.4. Config Client Retry
10.5. Locating Remote Configuration Resources
10.6. Security
10.6.1. Health Indicator
10.6.2. Providing A Custom RestTemplate
10.6.3. Vault
10.7. Vault
10.7.1. Nested Keys In Vault
III. Spring Cloud Netflix
11. Service Discovery: Eureka Clients
11.1. How to Include Eureka Client
11.2. Registering with Eureka
11.3. Authenticating with the Eureka Server
11.4. Status Page and Health Indicator
11.5. Registering a Secure Application
11.6. Eureka’s Health Checks
11.7. Eureka Metadata for Instances and Clients
11.7.1. Using Eureka on Cloudfoundry
11.7.2. Using Eureka on AWS
11.7.3. Changing the Eureka Instance ID
11.8. Using the EurekaClient
11.8.1. EurekaClient without Jersey
11.9. Alternatives to the native Netflix EurekaClient
11.10. Why is it so Slow to Register a Service?
11.11. Zones
12. Service Discovery: Eureka Server
12.1. How to Include Eureka Server
12.2. How to Run a Eureka Server
12.3. High Availability, Zones and Regions
12.4. Standalone Mode
12.5. Peer Awareness
12.6. Prefer IP Address
13. Circuit Breaker: Hystrix Clients
13.1. How to Include Hystrix
13.2. Propagating the Security Context or using Spring Scopes
13.3. Health Indicator
13.4. Hystrix Metrics Stream
14. Circuit Breaker: Hystrix Dashboard
15. Hystrix Timeouts And Ribbon Clients
15.1. How to Include Hystrix Dashboard
15.2. Turbine
15.3. Turbine Stream
16. Client Side Load Balancer: Ribbon
16.1. How to Include Ribbon
16.2. Customizing the Ribbon Client
16.3. Customizing default for all Ribbon Clients
16.4. Customizing the Ribbon Client using properties
16.5. Using Ribbon with Eureka
16.6. Example: How to Use Ribbon Without Eureka
16.7. Example: Disable Eureka use in Ribbon
16.8. Using the Ribbon API Directly
16.9. Caching of Ribbon Configuration
16.10. How to Configure Hystrix thread pools
16.11. How to Provide a Key to Ribbon’s IRule
17. Declarative REST Client: Feign
17.1. How to Include Feign
17.2. Overriding Feign Defaults
17.3. Creating Feign Clients Manually
17.4. Feign Hystrix Support
17.5. Feign Hystrix Fallbacks
17.6. Feign and @Primary
17.7. Feign Inheritance Support
17.8. Feign request/response compression
17.9. Feign logging
18. External Configuration: Archaius
19. Router and Filter: Zuul
19.1. How to Include Zuul
19.2. Embedded Zuul Reverse Proxy
19.3. Zuul Http Client
19.4. Cookies and Sensitive Headers
19.5. Ignored Headers
19.6. Management Endpoints
19.6.1. Routes Endpoint
19.6.2. Filters Endpoint
19.7. Strangulation Patterns and Local Forwards
19.8. Uploading Files through Zuul
19.9. Query String Encoding
19.10. Plain Embedded Zuul
19.11. Disable Zuul Filters
19.12. Providing Hystrix Fallbacks For Routes
19.13. Zuul Timeouts
19.14. Rewriting Location header
19.15. Zuul Developer Guide
19.15.1. The Zuul Servlet
19.15.2. Zuul RequestContext
19.15.3. @EnableZuulProxy vs. @EnableZuulServer
19.15.4. @EnableZuulServer Filters
19.15.5. @EnableZuulProxy Filters
19.15.6. Custom Zuul Filter examples
19.15.7. How to Write a Pre Filter
19.15.8. How to Write a Route Filter
19.15.9. How to Write a Post Filter
19.15.10. How Zuul Errors Work
19.15.11. Zuul Eager Application Context Loading
20. Polyglot support with Sidecar
21. Metrics: Spectator, Servo, and Atlas
21.1. Dimensional vs. Hierarchical Metrics
21.2. Default Metrics Collection
21.3. Metrics Collection: Spectator
21.3.1. Spectator Counter
21.3.2. Spectator Timer
21.3.3. Spectator Gauge
21.3.4. Spectator Distribution Summaries
21.4. Metrics Collection: Servo
21.4.1. Creating Servo Monitors
21.5. Metrics Backend: Atlas
21.5.1. Global tags
21.5.2. Using Atlas
21.6. Retrying Failed Requests
21.6.1. BackOff Policies
21.6.2. Configuration
21.6.3. Zuul
22. HTTP Clients
IV. Spring Cloud Stream
23. Introducing Spring Cloud Stream
24. Main Concepts
24.1. Application Model
24.1.1. Fat JAR
24.2. The Binder Abstraction
24.3. Persistent Publish-Subscribe Support
24.4. Consumer Groups
24.5. Consumer Types
24.5.1. Durability
24.6. Partitioning Support
25. Programming Model
25.1. Declaring and Binding Producers and Consumers
25.1.1. Triggering Binding Via @EnableBinding
25.1.2. @Input and @Output
Customizing Channel Names
Source, Sink, and Processor
25.1.3. Accessing Bound Channels
Injecting the Bound Interfaces
Injecting Channels Directly
25.1.4. Producing and Consuming Messages
Native Spring Integration Support
Spring Integration Error Channel Support
Message Channel Binders and Error Channels
Using @StreamListener for Automatic Content Type Handling
Using @StreamListener for dispatching messages to multiple methods
Using Polled Consumers
25.1.5. Reactive Programming Support
Reactor-based handlers
RxJava 1.x support
Reactive Sources
25.1.6. Aggregation
Configuring aggregate application
Configuring binding service properties for non self contained aggregate application
26. Binders
26.1. Producers and Consumers
26.2. Binder SPI
26.3. Binder Detection
26.3.1. Classpath Detection
26.4. Multiple Binders on the Classpath
26.5. Connecting to Multiple Systems
26.6. Binder configuration properties
27. Configuration Options
27.1. Spring Cloud Stream Properties
27.2. Binding Properties
27.2.1. Properties for Use of Spring Cloud Stream
27.2.2. Consumer properties
27.2.3. Producer Properties
27.3. Using dynamically bound destinations
28. Content Type and Transformation
28.1. MIME types
28.2. Channel contentType and Message Headers
28.3. ContentType handling for output channels
28.4. ContentType handling for input channels
28.5. Customizing message conversion
28.6. @StreamListener and Message Conversion
29. Schema evolution support
29.1. Apache Avro Message Converters
29.2. Converters with schema support
29.3. Schema Registry Support
29.4. Schema Registry Server
29.4.1. Schema Registry Server API
POST /
GET /{subject}/{format}/{version}
GET /{subject}/{format}
GET /schemas/{id}
DELETE /{subject}/{format}/{version}
DELETE /schemas/{id}
DELETE /{subject}
29.5. Schema Registry Client
29.5.1. Using Confluent’s Schema Registry
29.5.2. Schema Registry Client properties
29.6. Avro Schema Registry Client Message Converters
29.6.1. Avro Schema Registry Message Converter properties
29.7. Schema Registration and Resolution
29.7.1. Schema Registration Process (Serialization)
29.7.2. Schema Resolution Process (Deserialization)
30. Inter-Application Communication
30.1. Connecting Multiple Application Instances
30.2. Instance Index and Instance Count
30.3. Partitioning
30.3.1. Configuring Output Bindings for Partitioning
Configuring Input Bindings for Partitioning
31. Testing
31.1. Disabling the test binder autoconfiguration
32. Health Indicator
33. Metrics Emitter
34. Samples
35. Getting Started
35.1. Deploying Stream applications on CloudFoundry
V. Binder Implementations
36. Apache Kafka Binder
36.1. Usage
36.2. Apache Kafka Binder Overview
36.3. Configuration Options
36.3.1. Kafka Binder Properties
36.3.2. Kafka Consumer Properties
36.3.3. Kafka Producer Properties
36.3.4. Usage examples
Example: Setting autoCommitOffset false and relying on manual acking.
Example: security configuration
Example: Pausing and Resuming the Consumer
Using the binder with Apache Kafka 0.10
Excluding Kafka broker jar from the classpath of the binder based application
36.4. Kafka Streams Binding Capabilities of Spring Cloud Stream
36.4.1. Usage example of high level streams DSL
36.4.2. Message conversion in Spring Cloud Stream Kafka Streams applications
36.4.3. Support for branching in Kafka Streams API
36.4.4. Support for interactive queries
36.4.5. Kafka Streams properties
36.5. Error Channels
36.6. Kafka Metrics
36.7. Dead-Letter Topic Processing
36.8. Partitioning with the Kafka Binder
37. RabbitMQ Binder
37.1. Usage
37.2. RabbitMQ Binder Overview
37.3. Configuration Options
37.3.1. RabbitMQ Binder Properties
37.3.2. RabbitMQ Consumer Properties
37.3.3. Rabbit Producer Properties
37.4. Retry With the RabbitMQ Binder
37.4.1. Overview
37.4.2. Putting it All Together
37.5. Error Channels
37.6. Dead-Letter Queue Processing
37.6.1. Non-Partitioned Destinations
37.6.2. Partitioned Destinations
republishToDlq=false
republishToDlq=true
37.7. Partitioning with the RabbitMQ Binder
VI. Spring Cloud Bus
38. Quick Start
39. Addressing an Instance
40. Addressing all instances of a service
41. Service ID must be unique
42. Customizing the Message Broker
43. Tracing Bus Events
44. Broadcasting Your Own Events
44.1. Registering events in custom packages
VII. Spring Cloud Sleuth
45. Introduction
45.1. Terminology
45.2. Purpose
45.2.1. Distributed tracing with Zipkin
45.2.2. Visualizing errors
45.2.3. Distributed tracing with Brave
45.2.4. Live examples
45.2.5. Log correlation
JSON Logback with Logstash
45.2.6. Propagating Span Context
Baggage vs. Span Tags
45.3. Adding to the project
45.3.1. Only Sleuth (log correlation)
45.3.2. Sleuth with Zipkin via HTTP
45.3.3. Sleuth with Zipkin via RabbitMQ or Kafka
46. Additional resources
47. Features
47.1. Introduction to Brave
47.1.1. Tracing
47.1.2. Tracing
47.1.3. Local Tracing
47.1.4. Customizing spans
47.1.5. Implicitly looking up the current span
47.1.6. RPC tracing
One-Way tracing
48. Sampling
48.1. Declarative sampling
48.2. Custom sampling
48.3. Sampling in Spring Cloud Sleuth
49. Propagation
49.1. Propagating extra fields
49.1.1. Prefixed fields
49.1.2. Extracting a propagated context
49.1.3. Sharing span IDs between client and server
49.1.4. Implementing Propagation
50. Current Tracing Component
51. Current Span
51.1. Setting a span in scope manually
52. Instrumentation
53. Span lifecycle
53.1. Creating and finishing spans
53.2. Continuing spans
53.3. Creating spans with an explicit parent
54. Naming spans
54.1. @SpanName annotation
54.2. toString() method
55. Managing spans with annotations
55.1. Rationale
55.2. Creating new spans
55.3. Continuing spans
55.4. More advanced tag setting
55.4.1. Custom extractor
55.4.2. Resolving expressions for value
55.4.3. Using toString method
56. Customizations
56.1. Spring Integration
56.2. HTTP
56.3. TraceFilter
56.4. Custom service name
56.5. Customization of reported spans
56.6. Host locator
57. Sending spans to Zipkin
58. Zipkin Stream Span Consumer
59. Integrations
59.1. OpenTracing
59.2. Runnable and Callable
59.3. Hystrix
59.3.1. Custom Concurrency Strategy
59.3.2. Manual Command setting
59.4. RxJava
59.5. HTTP integration
59.5.1. HTTP Filter
59.5.2. HandlerInterceptor
59.5.3. Async Servlet support
59.5.4. WebFlux support
59.6. HTTP client integration
59.6.1. Synchronous Rest Template
59.6.2. Asynchronous Rest Template
Multiple Asynchronous Rest Templates
59.6.3. WebClient
59.6.4. Traverson
59.7. Feign
59.8. Asynchronous communication
59.8.1. @Async annotated methods
59.8.2. @Scheduled annotated methods
59.8.3. Executor, ExecutorService and ScheduledExecutorService
Customization of Executors
59.9. Messaging
59.10. Zuul
60. Running examples
VIII. Spring Cloud Consul
61. Install Consul
62. Consul Agent
63. Service Discovery with Consul
63.1. How to activate
63.2. Registering with Consul
63.3. HTTP Health Check
63.3.1. Metadata and Consul tags
63.3.2. Making the Consul Instance ID Unique
63.4. Looking up services
63.4.1. Using Ribbon
63.4.2. Using the DiscoveryClient
64. Distributed Configuration with Consul
64.1. How to activate
64.2. Customizing
64.3. Config Watch
64.4. YAML or Properties with Config
64.5. git2consul with Config
64.6. Fail Fast
65. Consul Retry
66. Spring Cloud Bus with Consul
66.1. How to activate
67. Circuit Breaker with Hystrix
68. Hystrix metrics aggregation with Turbine and Consul
IX. Spring Cloud Zookeeper
69. Install Zookeeper
70. Service Discovery with Zookeeper
70.1. How to activate
70.2. Registering with Zookeeper
70.3. Using the DiscoveryClient
71. Using Spring Cloud Zookeeper with Spring Cloud Netflix Components
71.1. Ribbon with Zookeeper
72. Spring Cloud Zookeeper and Service Registry
72.1. Instance Status
73. Zookeeper Dependencies
73.1. Using the Zookeeper Dependencies
73.2. How to activate Zookeeper Dependencies
73.3. Setting up Zookeeper Dependencies
73.3.1. Aliases
73.3.2. Path
73.3.3. Load balancer type
73.3.4. Content-Type template and version
73.3.5. Default headers
73.3.6. Obligatory dependencies
73.3.7. Stubs
73.4. Configuring Spring Cloud Zookeeper Dependencies
74. Spring Cloud Zookeeper Dependency Watcher
74.1. How to activate
74.2. Registering a listener
74.3. Presence Checker
75. Distributed Configuration with Zookeeper
75.1. How to activate
75.2. Customizing
75.3. ACLs
X. Spring Cloud Security
76. Quickstart
76.1. OAuth2 Single Sign On
76.2. OAuth2 Protected Resource
77. More Detail
77.1. Single Sign On
77.2. Token Relay
77.2.1. Client Token Relay
77.2.2. Client Token Relay in Zuul Proxy
77.2.3. Resource Server Token Relay
78. Configuring Authentication Downstream of a Zuul Proxy
XI. Spring Cloud for Cloud Foundry
79. Discovery
80. Single Sign On
XII. Spring Cloud Contract
81. Spring Cloud Contract
82. Spring Cloud Contract Verifier Introduction
82.1. Why a Contract Verifier?
82.1.1. Testing issues
82.2. Purposes
82.3. How It Works
82.3.1. Defining the contract
82.3.2. Client Side
82.3.3. Server Side
82.4. Step-by-step Guide to Consumer Driven Contracts (CDC)
82.4.1. Technical note
82.4.2. Consumer side (Loan Issuance)
82.4.3. Producer side (Fraud Detection server)
82.4.4. Consumer Side (Loan Issuance) Final Step
82.5. Dependencies
82.6. Additional Links
82.6.1. Spring Cloud Contract video
82.6.2. Readings
82.7. Samples
83. Spring Cloud Contract FAQ
83.1. Why use Spring Cloud Contract Verifier and not X ?
83.2. I don’t want to write a contract in Groovy!
83.3. What is this value(consumer(), producer()) ?
83.4. How to do Stubs versioning?
83.4.1. API Versioning
83.4.2. JAR versioning
83.4.3. Dev or prod stubs
83.5. Common repo with contracts
83.5.1. Repo structure
83.5.2. Workflow
83.5.3. Consumer
83.5.4. Producer
83.6. Can I have multiple base classes for tests?
83.7. How can I debug the request/response being sent by the generated tests client?
83.7.1. How can I debug the mapping/request/response being sent by WireMock?
83.7.2. How can I see what got registered in the HTTP server stub?
83.7.3. Can I reference the request from the response?
83.7.4. Can I reference text from file?
84. Spring Cloud Contract Verifier Setup
84.1. Gradle Project
84.1.1. Prerequisites
84.1.2. Add Gradle Plugin with Dependencies
84.1.3. Gradle and Rest Assured 2.0
84.1.4. Snapshot Versions for Gradle
84.1.5. Add stubs
84.1.6. Run the Plugin
84.1.7. Default Setup
84.1.8. Configure Plugin
84.1.9. Configuration Options
84.1.10. Single Base Class for All Tests
84.1.11. Different Base Classes for Contracts
84.1.12. Invoking Generated Tests
84.1.13. Spring Cloud Contract Verifier on the Consumer Side
84.2. Maven Project
84.2.1. Add maven plugin
84.2.2. Maven and Rest Assured 2.0
84.2.3. Snapshot versions for Maven
84.2.4. Add stubs
84.2.5. Run plugin
84.2.6. Configure plugin
84.2.7. Configuration Options
84.2.8. Single Base Class for All Tests
84.2.9. Different base classes for contracts
84.2.10. Invoking generated tests
84.2.11. Maven Plugin and STS
84.2.12. Spring Cloud Contract Verifier on the Consumer Side
84.3. Stubs and Transitive Dependencies
84.4. Scenarios
84.5. Docker Project
84.5.1. Short intro to Maven, JARs and Binary storage
84.5.2. How it works
Environment Variables
84.5.3. Example of usage
84.5.4. Server side (nodejs)
85. Spring Cloud Contract Verifier Messaging
85.1. Integrations
85.2. Manual Integration Testing
85.3. Publisher-Side Test Generation
85.3.1. Scenario 1: No Input Message
85.3.2. Scenario 2: Output Triggered by Input
85.3.3. Scenario 3: No Output Message
85.4. Consumer Stub Generation
86. Spring Cloud Contract Stub Runner
86.1. Snapshot versions
86.2. Publishing Stubs as JARs
86.3. Stub Runner Core
86.3.1. Retrieving stubs
Stub downloading
Classpath scanning
86.3.2. Running stubs
Limitations
Running using main app
HTTP Stubs
Viewing registered mappings
Messaging Stubs
86.4. Stub Runner JUnit Rule
86.4.1. Maven settings
86.4.2. Providing fixed ports
86.4.3. Fluent API
86.4.4. Stub Runner with Spring
86.5. Stub Runner Spring Cloud
86.5.1. Stubbing Service Discovery
Test profiles and service discovery
86.5.2. Additional Configuration
86.6. Stub Runner Boot Application
86.6.1. How to use it?
Stub Runner Server
Spring Cloud CLI
86.6.2. Endpoints
HTTP
Messaging
86.6.3. Example
86.6.4. Stub Runner Boot with Service Discovery
86.7. Stubs Per Consumer
86.8. Common
86.8.1. Common Properties for JUnit and Spring
86.8.2. Stub Runner Stubs IDs
86.9. Stub Runner Docker
86.9.1. How to use it
86.9.2. Example of client side usage in a non JVM project
87. Stub Runner for Messaging
87.1. Stub triggering
87.1.1. Trigger by Label
87.1.2. Trigger by Group and Artifact Ids
87.1.3. Trigger by Artifact Ids
87.1.4. Trigger All Messages
87.2. Stub Runner Integration
87.2.1. Adding the Runner to the Project
87.2.2. Disabling the functionality
Scenario 1 (no input message)
Scenario 2 (output triggered by input)
Scenario 3 (input with no output)
87.3. Stub Runner Stream
87.3.1. Adding the Runner to the Project
87.3.2. Disabling the functionality
Scenario 1 (no input message)
Scenario 2 (output triggered by input)
Scenario 3 (input with no output)
87.4. Stub Runner Spring AMQP
87.4.1. Adding the Runner to the Project
Triggering the message
Spring AMQP Test Configuration
88. Contract DSL
88.1. Limitations
88.2. Common Top-Level elements
88.2.1. Description
88.2.2. Name
88.2.3. Ignoring Contracts
88.2.4. Passing Values from Files
88.2.5. HTTP Top-Level Elements
88.3. Request
88.4. Response
88.5. Dynamic properties
88.5.1. Dynamic properties inside the body
88.5.2. Regular expressions
88.5.3. Passing Optional Parameters
88.5.4. Executing Custom Methods on the Server Side
88.5.5. Referencing the Request from the Response
88.5.6. Registering Your Own WireMock Extension
88.5.7. Dynamic Properties in the Matchers Sections
88.6. JAX-RS Support
88.7. Async Support
88.8. Working with Context Paths
88.9. Messaging Top-Level Elements
88.9.1. Output Triggered by a Method
88.9.2. Output Triggered by a Message
88.9.3. Consumer/Producer
88.9.4. Common
88.10. Multiple Contracts in One File
89. Customization
89.1. Extending the DSL
89.1.1. Common JAR
89.1.2. Adding the Dependency to the Project
89.1.3. Test the Dependency in the Project’s Dependencies
89.1.4. Test a Dependency in the Plugin’s Dependencies
89.1.5. Referencing classes in DSLs
90. Using the Pluggable Architecture
90.1. Custom Contract Converter
90.1.1. Pact Converter
90.1.2. Pact Contract
90.1.3. Pact for Producers
90.1.4. Pact for Consumers
90.2. Using the Custom Test Generator
90.3. Using the Custom Stub Generator
90.4. Using the Custom Stub Runner
90.5. Using the Custom Stub Downloader
91. Spring Cloud Contract WireMock
91.1. Registering Stubs Automatically
91.2. Using Files to Specify the Stub Bodies
91.3. Alternative: Using JUnit Rules
91.4. Relaxed SSL Validation for Rest Template
91.5. WireMock and Spring MVC Mocks
91.6. Customization of WireMock configuration
91.7. Generating Stubs using REST Docs
91.8. Generating Contracts by Using REST Docs
92. Migrations
92.1. 1.0.x → 1.1.x
92.1.1. New structure of generated stubs
92.2. 1.1.x → 1.2.x
92.2.1. Custom HttpServerStub
92.2.2. New packages for generated tests
92.2.3. New Methods in TemplateProcessor
92.2.4. RestAssured 3.0
92.3. 1.2.x → 2.0.x
92.3.1. No Camel support
93. Links
XIII. Spring Cloud Vault
94. Quick Start
95. Client Side Usage
95.1. Authentication
96. Authentication methods
96.1. Token authentication
96.2. AppId authentication
96.2.1. Custom UserId
96.3. AppRole authentication
96.4. AWS-EC2 authentication
96.5. AWS-IAM authentication
96.6. TLS certificate authentication
96.7. Cubbyhole authentication
96.8. Kubernetes authentication
97. Secret Backends
97.1. Generic Backend
97.2. Consul
97.3. RabbitMQ
97.4. AWS
98. Database backends
98.1. Database
98.2. Apache Cassandra
98.3. MongoDB
98.4. MySQL
98.5. PostgreSQL
99. Configure PropertySourceLocator behavior
100. Service Registry Configuration
101. Vault Client Fail Fast
102. Vault Client SSL configuration
103. Lease lifecycle management (renewal and revocation)
XIV. Spring Cloud Gateway
104. How to Include Spring Cloud Gateway
105. Glossary
106. How It Works
107. Route Predicate Factories
107.1. After Route Predicate Factory
107.2. Before Route Predicate Factory
107.3. Between Route Predicate Factory
107.4. Cookie Route Predicate Factory
107.5. Header Route Predicate Factory
107.6. Host Route Predicate Factory
107.7. Method Route Predicate Factory
107.8. Path Route Predicate Factory
107.9. Query Route Predicate Factory
107.10. RemoteAddr Route Predicate Factory
108. GatewayFilter Factories
108.1. AddRequestHeader GatewayFilter Factory
108.2. AddRequestParameter GatewayFilter Factory
108.3. AddResponseHeader GatewayFilter Factory
108.4. Hystrix GatewayFilter Factory
108.5. PrefixPath GatewayFilter Factory
108.6. PreserveHostHeader GatewayFilter Factory
108.7. RequestRateLimiter GatewayFilter Factory
108.8. RedirectTo GatewayFilter Factory
108.9. RemoveNonProxyHeaders GatewayFilter Factory
108.10. RemoveRequestHeader GatewayFilter Factory
108.11. RemoveResponseHeader GatewayFilter Factory
108.12. RewritePath GatewayFilter Factory
108.13. SaveSession GatewayFilter Factory
108.14. SecureHeaders GatewayFilter Factory
108.15. SetPath GatewayFilter Factory
108.16. SetResponseHeader GatewayFilter Factory
108.17. SetStatus GatewayFilter Factory
109. Global Filters
109.1. Combined Global Filter and GatewayFilter Ordering
109.2. Forward Routing Filter
109.3. LoadBalancerClient Filter
109.4. Netty Routing Filter
109.5. Netty Write Response Filter
109.6. RouteToRequestUrl Filter
109.7. Websocket Routing Filter
110. Configuration
110.1. Fluent Java Routes API
110.2. DiscoveryClient Route Definition Locator
111. Actuator API
112. Developer Guide
112.1. Writing Custom Route Predicate Factories
112.2. Writing Custom GatewayFilter Factories
112.3. Writing Custom Global Filters
112.4. Writing Custom Route Locators and Writers
113. Building a Simple Gateway Using Spring MVC
XV. Appendix: Compendium of Configuration Properties

Spring Cloud provides tools for developers to quickly build some of the common patterns in distributed systems (e.g. configuration management, service discovery, circuit breakers, intelligent routing, micro-proxy, control bus). Coordination of @@ -11869,7 +11869,335 @@ to false. This is not recommended as leases can exp Spring Cloud Vault cannot longer access Vault or services using generated credentials and valid credentials remain active after application shutdown.

spring.cloud.vault:
-    config.lifecycle.enabled: true

See also: Vault Documentation: Lease, Renew, and Revoke

Part XIV. Appendix: Compendium of Configuration Properties

NameDefaultDescription

encrypt.fail-on-error

true

Flag to say that a process should fail if there is an encryption or decryption + config.lifecycle.enabled: true

See also: Vault Documentation: Lease, Renew, and Revoke

Part XIV. Spring Cloud Gateway

1.3.5.BUILD-SNAPSHOT

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

104. How to Include Spring Cloud Gateway

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

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

105. Glossary

  • Route: Route the basic building block of the gateway. It is defined by an ID, a destination URI, a collection of predicates and a collection of filters. A route is matched if aggregate predicate is true.
  • Predicate: This is a Java 8 Function Predicate. The input type is a Spring Framework ServerWebExchange. This allows developers to match on anything from the HTTP request, such as headers or parameters.
  • Filter: These are instances Spring Framework GatewayFilter constructed in with a specific factory. Here, requests and responses can be modified before or after sending the downstream request.

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

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

107.1 After Route Predicate Factory

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

application.yml.  +

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

+

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

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

application.yml.  +

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

+

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

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

application.yml.  +

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

+

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

107.4 Cookie Route Predicate Factory

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

application.yml.  +

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

+

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

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

application.yml.  +

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

+

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

107.6 Host Route Predicate Factory

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

application.yml.  +

spring:
+  cloud:
+    gateway:
+      routes:
+      - id: host_route
+        uri: http://example.org
+        predicates:
+        - Host=**.somehost.org

+

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

107.7 Method Route Predicate Factory

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

application.yml.  +

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

+

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

107.8 Path Route Predicate Factory

The Path Route Predicate Factory takes one parameter: a Spring PathMatcher pattern.

application.yml.  +

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

+

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

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

107.9 Query Route Predicate Factory

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

application.yml.  +

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

+

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

application.yml.  +

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

+

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

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

application.yml.  +

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

+

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

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

108.1 AddRequestHeader GatewayFilter Factory

The AddRequestHeader GatewayFilter Factory takes a name and value parameter.

application.yml.  +

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

+

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

108.2 AddRequestParameter GatewayFilter Factory

The AddRequestParameter GatewayFilter Factory takes a name and value parameter.

application.yml.  +

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

+

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

108.3 AddResponseHeader GatewayFilter Factory

The AddResponseHeader GatewayFilter Factory takes a name and value parameter.

application.yml.  +

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

+

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

108.4 Hystrix GatewayFilter Factory

The Hystrix GatewayFilter Factory takes a single name parameters, which is the name of the HystrixCommand. (More options might be added in future releases).

application.yml.  +

spring:
+  cloud:
+    gateway:
+      routes:
+      - id: hytstrix_route
+        uri: http://example.org
+        filters:
+        - Hystrix=myCommandName

+

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

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

application.yml.  +

spring:
+  cloud:
+    gateway:
+      routes:
+      - id: hytstrix_route
+        uri: http://example.org
+        filters:
+        - name: Hystrix
+          args:
+            name: fallbackcmd
+            fallbackUri: forward:/fallbackcontroller
+
+This will forward to the `/fallbackcontroller` when the Hystrix fallback is called.

+

108.5 PrefixPath GatewayFilter Factory

The PrefixPath GatewayFilter Factory takes a single prefix parameter.

application.yml.  +

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

+

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

108.6 PreserveHostHeader GatewayFilter Factory

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

application.yml.  +

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

+

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

108.7 RequestRateLimiter GatewayFilter Factory

The RequestRateLimiter GatewayFilter Factory takes three parameters: replenishRate, burstCapacity & keyResolverName.

replenishRate is how many requests per second do you want a user to be allowed to do.

burstCapacity TODO: document burst capacity

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

KeyResolver.java.  +

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

+

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

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

application.yml.  +

spring:
+  cloud:
+    gateway:
+      routes:
+      - id: requestratelimiter_route
+        uri: http://example.org
+        filters:
+        - RequestRateLimiter=10, 20, #{@userKeyResolver}

+

Config.java.  +

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

+

This defines a request rate limit of 10 per user. The KeyResolver is a simple one that gets the user request parameter (note: this is not recommended for production).

108.8 RedirectTo GatewayFilter Factory

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

application.yml.  +

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

+

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

108.9 RemoveNonProxyHeaders GatewayFilter Factory

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

The default removed headers are:

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

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

108.10 RemoveRequestHeader GatewayFilter Factory

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

application.yml.  +

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

+

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

108.11 RemoveResponseHeader GatewayFilter Factory

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

application.yml.  +

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

+

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

108.12 RewritePath GatewayFilter Factory

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

application.yml.  +

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

+

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

108.13 SaveSession GatewayFilter Factory

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

application.yml.  +

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

+

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

108.14 SecureHeaders GatewayFilter Factory

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

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

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

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

Property to change:

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

108.15 SetPath GatewayFilter Factory

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

application.yml.  +

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

+

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

108.16 SetResponseHeader GatewayFilter Factory

The SetResponseHeader GatewayFilter Factory takes name and value parameters.

application.yml.  +

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

+

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

108.17 SetStatus GatewayFilter Factory

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

application.yml.  +

spring:
+  cloud:
+    gateway:
+      routes:
+      - id: setstatusstring_route
+        uri: http://example.org
+        filters:
+        - SetStatus=BAD_REQUEST
+      - id: setstatusint_route
+        uri: http://example.org
+        filters:
+        - SetStatus=401

+

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

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

109.1 Combined Global Filter and GatewayFilter Ordering

TODO: document ordering

109.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 unmodified original url is appended to the list in the ServerWebExchangeUtils.GATEWAY_ORIGINAL_REQUEST_URL_ATTR attribute.

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

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

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

109.6 RouteToRequestUrl Filter

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

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

109.7 Websocket Routing Filter

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

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

110. Configuration

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

RouteDefinitionLocator.java.  +

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

+

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

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

application.yml.  +

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

+

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

110.1 Fluent Java Routes API

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

GatewaySampleApplication.java.  +

// static imports from GatewayFilters and RoutePredicates
+@Bean
+public RouteLocator customRouteLocator(ThrottleGatewayFilterFactory throttle) {
+    return Routes.locator()
+            .route("test")
+                .predicate(host("**.abc.org").and(path("/image/png")))
+                .addResponseHeader("X-TestHeader", "foobar")
+                .uri("http://httpbin.org:80")
+            .route("test2")
+                .predicate(path("/image/webp"))
+                .add(addResponseHeader("X-AnotherHeader", "baz"))
+                .uri("http://httpbin.org:80")
+            .route("test3")
+                .order(-1)
+                .predicate(host("**.throttle.org").and(path("/get")))
+                .add(throttle.apply(tuple().of("capacity", 1,
+                     "refillTokens", 1,
+                     "refillPeriod", 10,
+                     "refillUnit", "SECONDS")))
+                .uri("http://httpbin.org:80")
+            .build();
+}

+

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

110.2 DiscoveryClient Route Definition Locator

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

111. Actuator API

TODO: document the /gateway actuator endpoint

112. Developer Guide

TODO: overview of writing custom integrations

112.1 Writing Custom Route Predicate Factories

TODO: document writing Custom Route Predicate Factories

112.2 Writing Custom GatewayFilter Factories

TODO: document writing Custom GatewayFilter Factories

112.3 Writing Custom Global Filters

TODO: document writing Custom Global Filters

112.4 Writing Custom Route Locators and Writers

TODO: document writing Custom Route Locators and Writers

113. Building a Simple Gateway Using Spring MVC

Spring Cloud Gateway provides a utility object called ProxyExchange which you can use inside a regular Spring MVC handler as a method parameter. It supports basic downstream HTTP exchanges via methods that mirror the HTTP verbs, or forwarding to a local handler via the forward() method.

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

@RestController
+@SpringBootApplication
+public class GatewaySampleApplication {
+
+	@Value("${remote.home}")
+	private URI home;
+
+	@GetMapping("/test")
+	public ResponseEntity<?> proxy(ProxyExchange<Object> proxy) throws Exception {
+		return proxy.uri(home.toString() + "/image/png").get();
+	}
+
+}

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

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

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

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

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

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

Part XV. Appendix: Compendium of Configuration Properties

NameDefaultDescription

encrypt.fail-on-error

true

Flag to say that a process should fail if there is an encryption or decryption error.

encrypt.key

 

A symmetric key. As a stronger alternative consider using a keystore.

encrypt.key-store.alias

 

Alias for a key in the store.

encrypt.key-store.location

 

Location of the key store file, e.g. classpath:/keystore.jks.

encrypt.key-store.password

 

Password that locks the keystore.

encrypt.key-store.secret

 

Secret protecting the key (defaults to the same as the password).

encrypt.rsa.algorithm

 

The RSA algorithm to use (DEFAULT or OEAP). Once it is set do not change it (or existing ciphers will not a decryptable).

encrypt.rsa.salt

deadbeef

Salt for the random secret used to encrypt cipher text. Once it is set do not change it (or existing ciphers will not a decryptable).

encrypt.rsa.strong

false

Flag to indicate that "strong" AES encryption should be used internally. If diff --git a/Finchley.M6/spring-cloud.xml b/Finchley.M6/spring-cloud.xml index cfd4e216..1a1a080b 100644 --- a/Finchley.M6/spring-cloud.xml +++ b/Finchley.M6/spring-cloud.xml @@ -22323,6 +22323,819 @@ after application shutdown. See also: Vault Documentation: Lease, Renew, and Revoke + +Spring Cloud Gateway + +1.3.5.BUILD-SNAPSHOT +This project provides an API Gateway built on top of the Spring Ecosystem, including: Spring 5, Spring Boot 2 and Project Reactor. Spring Cloud Gateway aims to provide a simple, yet effective way to route to APIs and provide cross cutting concerns to them such as: security, monitoring/metrics, and resiliency. + + +How to Include Spring Cloud Gateway +To include Spring Cloud Gateway in your project use the starter with group org.springframework.cloud +and artifact id spring-cloud-starter-gateway. See the Spring Cloud Project page +for details on setting up your build system with the current Spring Cloud Release Train. +If you include the starter, but, for some reason, you do not want the gateway to be enabled, set spring.cloud.gateway.enabled=false. + + +Glossary + + +Route: Route the basic building block of the gateway. It is defined by an ID, a destination URI, a collection of predicates and a collection of filters. A route is matched if aggregate predicate is true. + + +Predicate: This is a Java 8 Function Predicate. The input type is a Spring Framework ServerWebExchange. This allows developers to match on anything from the HTTP request, such as headers or parameters. + + +Filter: These are instances Spring Framework GatewayFilter constructed in with a specific factory. Here, requests and responses can be modified before or after sending the downstream request. + + + + +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. + + +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 +The After Route Predicate Factory takes one parameter, a datetime. This predicate matches requests that happen after the current datetime. + +application.yml + +spring: + cloud: + gateway: + routes: + - id: after_route + uri: http://example.org + predicates: + - After=2017-01-20T17:42:47.789-07:00[America/Denver] + + +This route matches any request after Jan 20, 2017 17:42 Mountain Time (Denver). +
+
+Before Route Predicate Factory +The Before Route Predicate Factory takes one parameter, a datetime. This predicate matches requests that happen before the current datetime. + +application.yml + +spring: + cloud: + gateway: + routes: + - id: before_route + uri: http://example.org + predicates: + - Before=2017-01-20T17:42:47.789-07:00[America/Denver] + + +This route matches any request before Jan 20, 2017 17:42 Mountain Time (Denver). +
+
+Between Route Predicate Factory +The Between Route Predicate Factory takes two parameters, datetime1 and datetime2. This predicate matches requests that happen after datetime1 and before datetime2. The datetime2 parameter must be after datetime1. + +application.yml + +spring: + cloud: + gateway: + routes: + - id: between_route + uri: http://example.org + predicates: + - Betweeen=2017-01-20T17:42:47.789-07:00[America/Denver], 2017-01-21T17:42:47.789-07:00[America/Denver] + + +This route matches any request after Jan 20, 2017 17:42 Mountain Time (Denver) and before Jan 21, 2017 17:42 Mountain Time (Denver). This could be useful for maintenance windows. +
+
+Cookie Route Predicate Factory +The Cookie Route Predicate Factory takes two parameters, the cookie name and a regular expression. This predicate matches cookies that have the given name and the value matches the regular expression. + +application.yml + +spring: + cloud: + gateway: + routes: + - id: cookie_route + uri: http://example.org + predicates: + - Cookie=chocolate, ch.p + + +This route matches the request has a cookie named chocolate who’s value matches the ch.p regular expression. +
+
+Header Route Predicate Factory +The Header Route Predicate Factory takes two parameters, the header name and a regular expression. This predicate matches with a header that has the given name and the value matches the regular expression. + +application.yml + +spring: + cloud: + gateway: + routes: + - id: header_route + uri: http://example.org + predicates: + - Header=X-Request-Id, \d+ + + +This route matches if the request has a header named X-Request-Id whos value matches the \d+ regular expression (has a value of one or more digits). +
+
+Host Route Predicate Factory +The Host Route Predicate Factory takes one parameter: the host name pattern. The pattern is an Ant style pattern with . as the separator. This predicates matches the Host header that matches the pattern. + +application.yml + +spring: + cloud: + gateway: + routes: + - id: host_route + uri: http://example.org + predicates: + - Host=**.somehost.org + + +This route would match if the request has a Host header has the value www.somehost.org or beta.somehost.org. +
+
+Method Route Predicate Factory +The Method Route Predicate Factory takes one parameter: the HTTP method to match. + +application.yml + +spring: + cloud: + gateway: + routes: + - id: method_route + uri: http://example.org + predicates: + - Method=GET + + +This route would match if the request method was a GET. +
+
+Path Route Predicate Factory +The Path Route Predicate Factory takes one parameter: a Spring PathMatcher pattern. + +application.yml + +spring: + cloud: + gateway: + routes: + - id: host_route + uri: http://example.org + predicates: + - Path=/foo/{segment} + + +This route would match if the request path was, for example: /foo/1 or /foo/bar. +This predicate extracts the URI template variables (like segment defined in the example above) as a map of names and values and places it in the ServerWebExchange.getAttributes() with a key defined in PathRoutePredicate.URL_PREDICATE_VARS_ATTR. Those values are then available for use by GatewayFilter Factories +
+
+Query Route Predicate Factory +The Query Route Predicate Factory takes two parameters: a required param and an optional regexp. + +application.yml + +spring: + cloud: + gateway: + routes: + - id: query_route + uri: http://example.org + predicates: + - Query=baz + + +This route would match if the request contained a baz query parameter. + +application.yml + +spring: + cloud: + gateway: + routes: + - id: query_route + uri: http://example.org + predicates: + - Query=foo, ba. + + +This route would match if the request contained a foo query parameter whose value matched the ba. regexp, so bar and baz would match. +
+
+RemoteAddr Route Predicate Factory +The RemoteAddr Route Predicate Factory takes a list (min size 1) of CIDR-notation (IPv4 or IPv6) strings, e.g. 192.168.0.1/16 (where 192.168.0.1 is an IP address and 16 is a subnet mask. + +application.yml + +spring: + cloud: + gateway: + routes: + - id: remoteaddr_route + uri: http://example.org + predicates: + - RemoteAddr=192.168.1.1/24 + + +This route would match if the remote address of the request was, for example, 192.168.1.10. +
+ + +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. +
+AddRequestHeader GatewayFilter Factory +The AddRequestHeader GatewayFilter Factory takes a name and value parameter. + +application.yml + +spring: + cloud: + gateway: + routes: + - id: add_request_header_route + uri: http://example.org + filters: + - AddRequestHeader=X-Request-Foo, Bar + + +This will add X-Request-Foo:Bar header to the downstream request’s headers for all matching requests. +
+
+AddRequestParameter GatewayFilter Factory +The AddRequestParameter GatewayFilter Factory takes a name and value parameter. + +application.yml + +spring: + cloud: + gateway: + routes: + - id: add_request_parameter_route + uri: http://example.org + filters: + - AddRequestParameter=foo, bar + + +This will add foo=bar to the downstream request’s query string for all matching requests. +
+
+AddResponseHeader GatewayFilter Factory +The AddResponseHeader GatewayFilter Factory takes a name and value parameter. + +application.yml + +spring: + cloud: + gateway: + routes: + - id: add_request_header_route + uri: http://example.org + filters: + - AddResponseHeader=X-Response-Foo, Bar + + +This will add X-Response-Foo:Bar header to the downstream response’s headers for all matching requests. +
+
+Hystrix GatewayFilter Factory +The Hystrix GatewayFilter Factory takes a single name parameters, which is the name of the HystrixCommand. (More options might be added in future releases). + +application.yml + +spring: + cloud: + gateway: + routes: + - id: hytstrix_route + uri: http://example.org + filters: + - Hystrix=myCommandName + + +This wraps the remaining filters in a HystrixCommand with command name myCommandName. +The Hystrix filter takes an optional fallbackUri parameter. Currently, only forward: schemed URIs are supported. If the fallback is called, the request will be forwarded to the controller matched by the URI. + +application.yml + +spring: + cloud: + gateway: + routes: + - id: hytstrix_route + uri: http://example.org + filters: + - name: Hystrix + args: + name: fallbackcmd + fallbackUri: forward:/fallbackcontroller + +This will forward to the `/fallbackcontroller` when the Hystrix fallback is called. + + +
+
+PrefixPath GatewayFilter Factory +The PrefixPath GatewayFilter Factory takes a single prefix parameter. + +application.yml + +spring: + cloud: + gateway: + routes: + - id: prefixpath_route + uri: http://example.org + filters: + - PrefixPath=/mypath + + +This will prefix /mypath to the path of all matching requests. So a request to /hello, would be sent to /mypath/hello. +
+
+PreserveHostHeader GatewayFilter Factory +The PreserveHostHeader GatewayFilter Factory has not parameters. This filter, sets a request attribute that the routing filter will inspect to determine if the original host header should be sent, rather than the host header determined by the http client. + +application.yml + +spring: + cloud: + gateway: + routes: + - id: preserve_host_route + uri: http://example.org + filters: + - PreserveHostHeader + + +This will prefix /mypath to the path of all matching requests. So a request to /hello, would be sent to /mypath/hello. +
+
+RequestRateLimiter GatewayFilter Factory +The RequestRateLimiter GatewayFilter Factory takes three parameters: replenishRate, burstCapacity & keyResolverName. +replenishRate is how many requests per second do you want a user to be allowed to do. +burstCapacity TODO: document burst capacity +keyResolver is a bean that implements the KeyResolver interface. In configuration, reference the bean by name using SpEL. #{@myKeyResolver} is a SpEL expression referencing a bean with the name myKeyResolver. + +KeyResolver.java + +public interface KeyResolver { + Mono<String> resolve(ServerWebExchange exchange); +} + + +The KeyResolver interface allows pluggable strategies to derive the key for limiting requests. In future milestones, there will be some KeyResolver implementations. +The 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. + +application.yml + +spring: + cloud: + gateway: + routes: + - id: requestratelimiter_route + uri: http://example.org + filters: + - RequestRateLimiter=10, 20, #{@userKeyResolver} + + + +Config.java + +@Bean +KeyResolver userKeyResolver() { + return exchange -> Mono.just(exchange.getRequest().getQueryParams().getFirst("user")); +} + + +This defines a request rate limit of 10 per user. The KeyResolver is a simple one that gets the user request parameter (note: this is not recommended for production). +
+
+RedirectTo GatewayFilter Factory +The RedirectTo GatewayFilter Factory takes a status and a url parameter. The status should be a 300 series redirect http code, such as 301. The url should be a valid url. This will be the value of the Location header. + +application.yml + +spring: + cloud: + gateway: + routes: + - id: prefixpath_route + uri: http://example.org + filters: + - RedirectTo=302, http://acme.org + + +This will send a status 302 with a Location:http://acme.org header to perform a redirect. +
+
+RemoveNonProxyHeaders GatewayFilter Factory +The RemoveNonProxyHeaders GatewayFilter Factory removes headers from forwarded requests. The default list of headers that is removed comes from the IETF. + +The default removed headers are: + +Connection + + +Keep-Alive + + +Proxy-Authenticate + + +Proxy-Authorization + + +TE + + +Trailer + + +Transfer-Encoding + + +Upgrade + + +To change this, set the spring.cloud.gateway.filter.remove-non-proxy-headers.headers property to the list of header names to remove. +
+
+RemoveRequestHeader GatewayFilter Factory +The RemoveRequestHeader GatewayFilter Factory takes a name parameter. It is the name of the header to be removed. + +application.yml + +spring: + cloud: + gateway: + routes: + - id: removerequestheader_route + uri: http://example.org + filters: + - RemoveRequestHeader=X-Request-Foo + + +This will remove the X-Request-Foo header before it is sent downstream. +
+
+RemoveResponseHeader GatewayFilter Factory +The RemoveResponseHeader GatewayFilter Factory takes a name parameter. It is the name of the header to be removed. + +application.yml + +spring: + cloud: + gateway: + routes: + - id: removeresponseheader_route + uri: http://example.org + filters: + - RemoveResponseHeader=X-Response-Foo + + +This will remove the X-Response-Foo header from the response before it is returned to the gateway client. +
+
+RewritePath GatewayFilter Factory +The RewritePath GatewayFilter Factory takes a path regexp parameter and a replacement parameter. This uses Java regular expressions for a flexible way to rewrite the request path. + +application.yml + +spring: + cloud: + gateway: + routes: + - id: rewritepath_route + uri: http://example.org + predicates: + - Path=/foo/** + filters: + - RewritePath=/foo/(?<segment>.*), /$\{segment} + + +For a request path of /foo/bar, this will set the path to /bar before making the downstream request. Notice the $\ which is replaced with $ because of the YAML spec. +
+
+SaveSession GatewayFilter Factory +The SaveSession GatewayFilter Factory forces a WebSession::save operation before forwarding the call downstream. This is of particular use when +using something like Spring Session with a lazy data store and need to ensure the session state has been saved before making the forwarded call. + +application.yml + +spring: + cloud: + gateway: + routes: + - id: save_session + uri: http://example.org + predicates: + - Path=/foo/** + filters: + - SaveSession + + +If you are integrating Spring Security with Spring Session, and want to ensure security details have been forwarded to the remote process, this is critical. +
+
+SecureHeaders GatewayFilter Factory +The SecureHeaders GatewayFilter Factory adds a number of headers to the response at the reccomendation from this blog post. + +The following headers are added (allong with default values): + +X-Xss-Protection:1; mode=block + + +Strict-Transport-Security:max-age=631138519 + + +X-Frame-Options:DENY + + +X-Content-Type-Options:nosniff + + +Referrer-Policy:no-referrer + + +Content-Security-Policy:default-src 'self' https:; font-src 'self' https: data:; img-src 'self' https: data:; object-src 'none'; script-src https:; style-src 'self' https: 'unsafe-inline' + + +X-Download-Options:noopen + + +X-Permitted-Cross-Domain-Policies:none + + +To change the default values set the appropriate property in the spring.cloud.gateway.filter.secure-headers namespace: + +Property to change: + +xss-protection-header + + +strict-transport-security + + +frame-options + + +content-type-options + + +referrer-policy + + +content-security-policy + + +download-options + + +permitted-cross-domain-policies + + +
+
+SetPath GatewayFilter Factory +The SetPath GatewayFilter Factory takes a path template parameter. It offers a simple way to manipulate the request path by allowing templated segments of the path. This uses the uri templates from Spring Framework. Multiple matching segments are allowed. + +application.yml + +spring: + cloud: + gateway: + routes: + - id: setpath_route + uri: http://example.org + predicates: + - Path=/foo/{segment} + filters: + - SetPath=/{segment} + + +For a request path of /foo/bar, this will set the path to /bar before making the downstream request. +
+
+SetResponseHeader GatewayFilter Factory +The SetResponseHeader GatewayFilter Factory takes name and value parameters. + +application.yml + +spring: + cloud: + gateway: + routes: + - id: setresponseheader_route + uri: http://example.org + filters: + - SetResponseHeader=X-Response-Foo, Bar + + +This GatewayFilter replaces all headers with the given name, rather than adding. So if the downstream server responded with a X-Response-Foo:1234, this would be replaced with X-Response-Foo:Bar, which is what the gateway client would receive. +
+
+SetStatus GatewayFilter Factory +The SetStatus GatewayFilter Factory takes a single status parameter. It must be a valid Spring HttpStatus. It may be the integer value 404 or the string representation of the enumeration NOT_FOUND. + +application.yml + +spring: + cloud: + gateway: + routes: + - id: setstatusstring_route + uri: http://example.org + filters: + - SetStatus=BAD_REQUEST + - id: setstatusint_route + uri: http://example.org + filters: + - SetStatus=401 + + +In either case, the HTTP status of the response will be set to 401. +
+
+ +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 +TODO: document ordering +
+
+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 unmodified original url is appended to the list in the ServerWebExchangeUtils.GATEWAY_ORIGINAL_REQUEST_URL_ATTR attribute. +
+
+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. +
+
+Netty Routing Filter +The Netty Routing Filter runs if the url located in the ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR exchange attribute has a http or https scheme. It uses the Netty HttpClient to make the downstream proxy request. The response is put in the ServerWebExchangeUtils.CLIENT_RESPONSE_ATTR exchange attribute for use in a later filter. (There is an experimental WebClientHttpRoutingFilter that performs the same function, but does not require netty) +
+
+Netty Write Response Filter +The NettyWriteResponseFilter runs if there is a Netty HttpClientResponse in the ServerWebExchangeUtils.CLIENT_RESPONSE_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 +The RouteToRequestUrlFilter runs if there is a Route object in the ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR exchange attribute. It creates a new URI, based off of the request URI, but updated with the URI attribute of the Route object. The new URI is placed in the ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR exchange attribute`. +If the URI has a scheme prefix, such as lb:ws://serviceid, the lb scheme is stripped from the URI and placed in the ServerWebExchangeUtils.GATEWAY_SCHEME_PREFIX_ATTR for use later in the filter chain. +
+
+Websocket Routing Filter +The Websocket Routing Filter runs if the url located in the ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR exchange attribute has a ws or wss scheme. It uses the Spring Web Socket infrastructure to forward the Websocket request downstream. +Websockets may be load-balanced by prefixing the URI with lb, such as lb:ws://serviceid. +
+
+ +Configuration +Configuration for Spring Cloud Gateway is driven by a collection of `RouteDefinitionLocator`s. + +RouteDefinitionLocator.java + +public interface RouteDefinitionLocator { + Flux<RouteDefinition> getRouteDefinitions(); +} + + +By default, a PropertiesRouteDefinitionLocator loads properties using Spring Boot’s @ConfigurationProperties mechanism. +The configuration examples above all use a shortcut notation that uses positional arguments rather than named ones. The two examples below are equivalent: + +application.yml + +spring: + cloud: + gateway: + routes: + - id: setstatus_route + uri: http://example.org + filters: + - name: SetStatus + args: + status: 401 + - id: setstatusshortcut_route + uri: http://example.org + filters: + - SetStatus=401 + + +For some usages of the gateway, properties will be adequate, but some production use cases will benefit from loading configuration from an external source, such as a database. Future milestone versions will have RouteDefinitionLocator implementations based off of Spring Data Repositories such as: Redis, MongoDB and Cassandra. +
+Fluent Java Routes API +To allow for simple configuration in Java, there is a fluent API defined in the Routes class. + +GatewaySampleApplication.java + +// static imports from GatewayFilters and RoutePredicates +@Bean +public RouteLocator customRouteLocator(ThrottleGatewayFilterFactory throttle) { + return Routes.locator() + .route("test") + .predicate(host("**.abc.org").and(path("/image/png"))) + .addResponseHeader("X-TestHeader", "foobar") + .uri("http://httpbin.org:80") + .route("test2") + .predicate(path("/image/webp")) + .add(addResponseHeader("X-AnotherHeader", "baz")) + .uri("http://httpbin.org:80") + .route("test3") + .order(-1) + .predicate(host("**.throttle.org").and(path("/get"))) + .add(throttle.apply(tuple().of("capacity", 1, + "refillTokens", 1, + "refillPeriod", 10, + "refillUnit", "SECONDS"))) + .uri("http://httpbin.org:80") + .build(); +} + + +This style also allows for more custom predicate assertions. The predicates defined by RouteDefinitionLocator beans are combined using logical and. By using the fluent Java API, you can use the and(), or() and negate() operators on the Predicate class. +
+
+DiscoveryClient Route Definition Locator +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). +
+
+ +Actuator API +TODO: document the /gateway actuator endpoint + + +Developer Guide +TODO: overview of writing custom integrations +
+Writing Custom Route Predicate Factories +TODO: document writing Custom Route Predicate Factories +
+
+Writing Custom GatewayFilter Factories +TODO: document writing Custom GatewayFilter Factories +
+
+Writing Custom Global Filters +TODO: document writing Custom Global Filters +
+
+Writing Custom Route Locators and Writers +TODO: document writing Custom Route Locators and Writers +
+
+ +Building a Simple Gateway Using Spring MVC +Spring Cloud Gateway provides a utility object called ProxyExchange which you can use inside a regular Spring MVC handler as a method parameter. It supports basic downstream HTTP exchanges via methods that mirror the HTTP verbs, or forwarding to a local handler via the forward() method. +Example (proxying a request to "/test" downstream to a remote server): +@RestController +@SpringBootApplication +public class GatewaySampleApplication { + + @Value("${remote.home}") + private URI home; + + @GetMapping("/test") + public ResponseEntity<?> proxy(ProxyExchange<Object> proxy) throws Exception { + return proxy.uri(home.toString() + "/image/png").get(); + } + +} +There are convenience methods on the ProxyExchange to enable the handler method to discover and enhance the URI path of the incoming request. For example you might want to extract the trailing elements of a path to pass them downstream: +@GetMapping("/proxy/path/**") +public ResponseEntity<?> proxyPath(ProxyExchange<?> proxy) throws Exception { + String path = proxy.path("/proxy/path/"); + return proxy.uri(home.toString() + "/foos/" + path).get(); +} +All the features of Spring MVC are available to Gateway handler methods. So you can inject request headers and query parameters, for instance, and you can constrain the incoming requests with declarations in the mapping annotation. See the documentation for @RequestMapping in Spring MVC for more details of those features. +Headers can be added to the downstream response using the header() methods on ProxyExchange. +You can also manipulate response headers (and anything else you like in the response) by adding a mapper to the get() etc. method. The mapper is a Function that takes the incoming ResponseEntity and converts it to an outgoing one. +First class support is provided for "sensitive" headers ("cookie" and "authorization" by default) which are not passed downstream, and for "proxy" headers (x-forwarded-*). + + Appendix: Compendium of Configuration Properties