=== High Availability, Zones and Regions
+diff --git a/spring-cloud.html b/spring-cloud.html index 2b17e25..df122cb 100644 --- a/spring-cloud.html +++ b/spring-cloud.html @@ -457,6 +457,70 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
SmartLifecycle (with phase=0) so t
you can rely on it being available is in another SmartLifecycle with
higher phase.
-=== Alternatives to the DiscoveryClient
+ + +You don’t have to use the raw Netflix DiscoveryClient and usually it
is more convenient to use it behind a wrapper of some sort. Spring
@@ -1487,9 +1555,9 @@ builder) and also Spring RestTemplate
=== Why is it so Slow to Register a Service?
Being an instance also involves a periodic heartbeat to the registry
(via the client’s serviceUrl) with default duration 30 seconds. A
@@ -1502,9 +1570,12 @@ production it’s probably better to stick with the default because
there are some computations internally in the server that make
assumptions about the lease renewal period.
== Service Discovery: Eureka Server
Example eureka server:
/eureka/*.
Eureka background reading: see flux capacitor and google group discussion.
|
+ Tip
|
-
You can run the Eureka server as an executable JAR (or WAR) using the Spring @@ -1573,11 +1647,46 @@ springBoot { }
=== High Availability, Zones and Regions
+|
+ Note
+ |
+
+
+
+The Eureka server is tied to log4j and doesn’t work with logback,
+so the dependency configuration
+has to be tweaked compared to a normal Spring Boot app. The
+
+
+pom.xml
+
+
+
+ |
+
The Eureka server does not have a backend store, but the service instances in the registry all have to send heartbeats to keep their @@ -1591,9 +1700,9 @@ go to the registry for every single request to a service).
the service will run and work, but it will shower your logs with a lot of noise about not being able to register with the peer.=== Standalone Mode
The combination of the two caches (client and server) and the heartbeats make a standalone Eureka server fairly resilient to @@ -1622,9 +1731,9 @@ eureka:
Notice that the serviceUrl is pointing to the same host as the local
instance.
=== Peer Awareness
Eureka can be made even more resilient and available by running multiple instances and asking them to register with each other. In @@ -1672,9 +1781,12 @@ the registrations amongst themselves. If the peers are physically separated (inside a data centre or between multiple data centres) then the system can in principle survive split-brain type failures.
== Circuit Breaker: Hystrix Clients
Netflix has created a library called Hystrix that implements the circuit breaker pattern. In a microservice architecture it is common to have multiple layers of service calls.
== Circuit Breaker: Hystrix Dashboard
One of the main benefits of Hystrix is the set of metrics it gathers about each HystrixCommand. The Hystrix Dashboard displays the health of each circuit breaker in an efficient manner.
To run the Hystrix Dashboard annotate your Spring Boot main class with @EnableHystrixDashboard. You then visit /hystrix/index.html and point the dashboard to an individual instances /hystrix.stream endpoint in a Hystrix client application.
=== Turbine
-Looking at an individual instances Hystrix data is not very useful in terms of the overall health of the system. Turbine is an application that aggregates all of the relevant /hystrix.stream endpoints into a combined /turbine.stream for use in the Hystrix Dashboard. Individual instances are located via Eureka. Running Turbine is as simple as annotating your main class with the @EnableTurbine annotation.
The clusterName can be customized by a SPEL expression in turbine.clusterNameExpression. For example, turbine.clusterNameExpression=aSGName would get the clustername from the AWS ASG name.
== Declarative REST Client: Feign
Feign is a declarative web service client. It makes writing web service clients easier. To use Feign create an interface and annotate it. It has pluggable annotation support including Feign annotations and JAX-RS annotations. Feign also supports pluggable encoders and decoders. Spring Cloud adds support for Spring MVC annotations and for using the same HttpMessageConverters used by default in Spring Web. Spring Cloud integrates Ribbon and Eureka to provide a load balanced http client when using Feign.
== Client Side Load Balancer: Ribbon
Usage of LoadBalancerClient directly:
== External Configuration: Archaius
Archaius is the Netflix client side configuration library. It is the library used by all of the Netflix OSS components for configuration. Archaius is an extension of the Apache Commons Configuration project. It allows updates to configuration by either polling a source for changes or for a source to push changes to the client. Archaius uses Dynamic<Type>Property classes as handles to properties.
Archaius has its own set of configuration files and loading priorities. Spring applications should generally not use Archaius directly., but the need to configure the Netflix tools natively remains. Spring Cloud has a Spring Environment Bridge so Archaius can read properties from the Spring Environment. This allows Spring Boot projects to use the normal configuration toolchain, while allowing them to configure the Netflix tools, for the most part, as documented.
== Router and Filter: Zuul
Routing in an integral part of a microservice architecture. For example, / may be mapped to your web application, /api/users is mapped to the user service and /api/shop is mapped to the shop service. Zuul is a JVM based router and server side load balancer by Netflix.
Zuul’s rule engine allows rules and filters to be written in essentially any JVM language, with built in support for Java and Groovy.
=== Embedded Zuul Reverse Proxy
-Spring Cloud has created an embedded Zuul proxy to ease the development of a very common use case where a UI application wants to proxy calls to one or more back end services. To enable it, annotate a Spring Boot main class with @EnableZuulProxy. This forwards local calls to /proxy/* to the appropriate service. The proxy uses Ribbon to locate an instance to forward to via Eureka. Forwarding to the service is protected by a Hystrix circuit breaker. Rules are configured via the Spring environment. The Config Server is an ideal place for the Zuul configuration. Zuul Embedded Proxy configuration rules look like the following:
This means that http calls to /proxy/users get forwarded to the users service. This proxy configuration is useful for services that host a user interface to proxy to the backend services it requires. By default, the proxy mapping gets stripped from the request before forwarding.
=== Standalone Zuul Server
Spring Cloud has created a standalone Zuul server. To enable it, annotate a Spring Boot main class with @EnableZuulServer. This routes all calls to the appropriate service. The server uses Ribbon to locate an instance to forward to via Eureka. Forwarding to the service is protected by a Hystrix circuit breaker. Rules are configured via the Spring environment. The Config Server is an ideal place for the Zuul configuration. Zuul Server configuration rules look like the following:
= Spring Cloud Cluster
Spring Cloud Cluster offers a set of primitives for building "cluster" -features into a distributed system. Example are leadership election, -consistent storage of cluster state, global locks and one-time tokens.
= Spring Cloud Bus -:toc:
Spring Cloud Bus links nodes of a distributed system with a lightweight message broker. This can then be used to broadcast state changes (e.g. configuration changes) or other management instructions. A key idea is that the Bus is like a distributed Actuator for a Spring Boot application that is scaled out, but it can also be used as a communication channel between apps. The only implementation currently is with an AMQP broker as the transport, but the same basic feature set (and some more depending on the transport) is on the roadmap for other transports.
+== Quick Start
Spring Cloud Bus works by adding Spring Boot autconfiguration if it detects itself on the classpath. All you need to do to enable the bus is to add spring-cloud-starter-bus-amqp to your dependency management and Spring Cloud takes care of the rest. Make sure RabbitMQ is available and configured to provide a ConnectionFactory: running on localhost you shouldn’t have to do anything, but if you are running remotely use Spring Cloud Connectors, or Spring Boot conventions to define the broker credentials, e.g.
The bus currently supports sending messages to all nodes listening or all nodes for a particular service (as defined by Eureka). More selector criteria will be added in the future (ie. only service X nodes in data center Y, etc…). The http endpoints are under the /bus/* actuator namespace. There are currently two implemented. The first, /bus/env, sends key/values pairs to update each nodes Spring Environment. The second, /bus/refresh, will reload each application’s configuration, just as if they had all been pinged on their /refresh endpoint.
= Spring Boot Cloud CLI
Spring Boot command line features for -Spring Cloud.
== Installation
+To install, make sure you have @@ -2061,13 +2178,12 @@ $ gvm use springboot 1.2.0.RC1 $ spring install org.springframework.cloud:spring-cloud-cli:1.0.0.BUILD-SNAPSHOT
= Spring Cloud Security -:github-base: https://github.com/spring-cloud -:security-base: https://github.com/spring-cloud/spring-cloud-security
Spring Cloud Security offers a set of primitives for building secure +
== Quickstart
-=== OAuth Single Sign On
Here’s a Spring Cloud "Hello World" app with HTTP Basic authentication and a single user account:
@@ -2156,46 +2272,15 @@ authenticated. These credentials will only work if your app is running on port 8080.If you now drop the app into Cloud Foundry:
-$ spring jar app.jar app.groovy -$ cf push -p app.jar-
and bind it to a service called "sso" with the following properties -(e.g. created as a -user-provided -service):
-$ cf create-user-provided-service sso -p '{clientId:"<my-client>",clientSecret:"<my-secret>",userInfoUri:"https://uaa.run.pivotal.io/userinfo",tokenUri: "https://login.run.pivotal.io/oauth/token",authorizationUri:"https://login.run.pivotal.io/oauth/authorize"}
-$ cf bind-service app sso
-$ cf push app -p app.jar
-and then visit it in a browser, then it will redirect to the Cloud
-Foundry (PWS) login server instead of challenging for Basic
-authentication credentials. The clientId and clientSecret are
-credentials of a registered client in Cloud Foundry. It’s quite hard
-to get a Cloud Foundry client registration for testing (but please ask
-at support@run.pivotal.io if you want one on PWS, or your local
-platform administrator if it’s a private instance).
To limit the scope that the client asks for when it obtains an access token
you can set oauth2.client.scope (comma separated or an array in YAML). By
default the scope is empty and it is up to to Authorization Server to
decide what the defaults should be, usually depending on the settings in
the client registration that it holds.
=== OAuth Protected Resource
You want to protect an API resource with an OAuth2 token? Here’s a simple example (paired with the client above):
@@ -2228,9 +2313,63 @@ class Application { preferTokenInfo: false=== Token Relay
An app will activate @EnableOAuth2Sso if you bind provide the
+following properties in the Environment:
oauth2.client.* with * equal to clientId, clientSecret,
+tokenUri and authorizationUri and;
oauth2.resource.preferTokenInfo=false and
+oauth2.resource.userInfoUri to use the "/me" resource
+(e.g. "https://uaa.run.pivotal.io/userinfo" on PWS), or
oauth2.resource.tokenInfoUri to use the token decoding endpoint
+(e.g. "https://uaa.run.pivotal.io/check_token" on PWS), or
oauth2.resource.jwt.keyValue or oauth2.resource.jwt.keyUri to
+decode a JWT token locally, where the key is a verification key. The
+verification key value is either a symmetric secret or PEM-encoded
+RSA public key. If you don’t have the key and it’s public you can
+provide a URI where it can be downloaded (as a JSON object with a
+"value" field). E.g. on PWS:
++
$ curl https://uaa.run.pivotal.io/token_key
+{"alg":"SHA256withRSA","value":"-----BEGIN PUBLIC KEY-----\nMIIBI...\n-----END PUBLIC KEY-----\n"}
+The @EnableOAuth2Resource annotation will protect your API endpoints
+if you have the same environment settings as the SSO client, except
+that it doesn’t need a tokenUri or authorizationUri, and it also
+doesn’t need a clientId and clientSecret if it isn’t using the
+tokenInfoUri (i.e. if it has jwt.* or userInfoUri).
If your app has a Spring @@ -2267,19 +2406,193 @@ correct header.
traditional app), and that has some autoconfiguration for aZuulFilter, which itself is activated because Zuul is on the
classpath (via @EnableZuulProxy). The
-{security-base}/tree/master/src/main/java/org/springframework/cloud/security/proxy/OAuth2TokenRelayFilter.java[filter]
+filter
just extracts an access token from the currently authenticated user,
and puts it in a request header for the downstream requests.
Spring Cloud for Cloudfoundry makes it easy to run +Spring Cloud apps in +Cloud Foundry (the Platform as a +Service). Cloud Foundry has the notion of a "service", which is +middlware that you "bind" to an app, essentially providing it with an +environment variable containing credentials (e.g. the location and +username to use for the service).
+Add this project as a dependency to any Spring Cloud UI app or REST
+service and deploy to Cloudfoundry. If you use Spring Cloud Security
+OAuth2 features this will make them bindable to Cloud Foundry services
+instead of enironment properties in oauth2.*. For a UI app you can
+declare @EnableOAuth2Sso and bind to a service called "sso", and for
+a service you can add @EnableOAuth2Resource and bind to a service
+called "resource" (see below for how to change the names).
Here’s a Spring Cloud app with OAuth2 SSO:
+@Controller
+@EnableOAuth2Sso
+class Application {
+
+ @RequestMapping('/')
+ String home() {
+ 'Hello World'
+ }
+
+}
+If you run it without any service bindings:
+$ spring jar app.jar app.groovy +$ cf push -p app.jar+
it will be secure with (Spring Boot default) Basic authentication,
+i.e. the password will be in the logs (or set it with
+security.user.password as normal). To turn on OAuth2 SSO all you
+need to do is bind the app to a service with the right
+credentials. For example, a
+user-provided
+service can be created like this on PWS:
$ cf create-user-provided-service sso -p '{clientId:"<my-client>",clientSecret:"<my-secret>",userInfoUri:"https://uaa.run.pivotal.io/userinfo",tokenUri: "https://login.run.pivotal.io/oauth/token",authorizationUri:"https://login.run.pivotal.io/oauth/authorize"}
+Then bind and restart the app:
+$ cf bind app sso +$ cf restart app+
and visit it in a browser. It will redirect to the Cloud Foundry (PWS)
+login server instead of challenging for Basic authentication. The
+clientId and clientSecret are credentials of a registered client
+in Cloud Foundry. To get a Cloud Foundry client registration for
+testing please ask at support@run.pivotal.io (if you want it on PWS),
+or your local platform administrator (if it’s a private instance).
Spring Cloud Security provides the @EnableOAuth2Sso annotation and
+binds the app to environment properties in oauth2.*. Spring Cloud
+for Cloud Foundry just sets up default environment properties so that
+it all just works if you bind to a Cloud Foundry service instance
+called "sso". The service credentials are mapped to the SSO
+properties, i.e. clientId, clientSecret, tokenUri,
+authorizationUri, userInfoUri, tokenInfoUri1, `jwt.\* (refer to
+the Spring Cloud Security documentation for details of which
+combinations will work together). The main thing is that in Cloud
+Foundry you only need one service to cover all the necessary
+credentials.
To use a different sercice instance name (i.e. not "sso") just set
+oauth2.sso.serviceId to your custom name.
Spring Cloud Security already has support for decoding JWT tokens if
+you just provide the verification key (as an environment property). In
+Cloud Foundry you can pick that property up from a servcice binding
+(jwt.keyValue or jwt.keyUri).
For example the jwt.keyUri in PWS is
+"https://uaa.run.pivotal.io/token_key":
$ curl https://uaa.run.pivotal.io/token_key
+{"alg":"SHA256withRSA","value":"-----BEGIN PUBLIC KEY-----\nMIIBI...\n-----END PUBLIC KEY-----\n"}d
+Similarly, the @EnableOAuth2Resource annotation will protect your
+API endpoints if you bind to a service instance called "resource".
+The "sso" service above will work for a resource server as well (so
+just bind to that if it’s there). If the OAuth2 tokens are JWTs (as in
+Cloud Foundry), it is common to use a separate service for resources
+to avoid a network round trip decoding the token on every access. A
+user-provided-service for an OAuth2 resource can be created like this
+on PWS:
$ cf create-user-provided-service resource -p '{jwt.keyUri:"https://uaa.run.pivotal.io/token_key"}
+To use JWT you need to add the verification key as either
+jwt.keyValue or jwt.keyUri (these could be added to the "sso"
+service or the "resource" service if you have one).
To use a different sercice instance name (i.e. not "resource" or
+"sso") just set oauth2.resource.serviceId to your custom name.
The precise mapppings are as follows:
+oauth2.sso.* to vcap.services.${oauth2.sso.serviceId:sso}.credentials.*
oauth2.client.* to vcap.services.${oauth2.sso.serviceId:sso}.credentials.tokenUri:${vcap.services.${oauth2.resource.serviceId:resource}.credentials.*
oauth2.resource.* to vcap.services.${oauth2.resource.serviceId:resource}.credentials.tokenUri:${vcap.services.${oauth2.sso.serviceId:sso}.credentials.*