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, one-time tokens, global locks, leadership election, distributed sessions, cluster state). Coordination of distributed systems leads to boiler plate patterns, and using Spring Cloud developers can quickly stand up services and applications that implement those patterns. They will work well in any distributed environment, including the developer’s own laptop, bare metal data centres, and managed platforms such as Cloud Foundry.
Features
Spring Cloud focuses on providing good out of box experience for typical use cases and extensibility mechanism to cover others.
-
Distributed/versioned configuration
-
Service registration and discovery
-
Routing
-
Service-to-service calls
-
Load balancing
-
Circuit Breakers
-
Global locks
-
Leadership election and cluster state
-
Distributed messaging
Spring Cloud Config
Environment and PropertySource abstractions, so they fit very well with Spring applications, but can be used with any application running in any language. As an application moves through the deployment pipeline from dev to test and into production you can manage the configuration between those environments and be certain that applications have everything they need to run when they migrate. The default implementation of the server storage backend uses git so it easily supports labelled versions of configuration environments, as well as being accessible to a wide range of tooling for managing the content. It is easy to add alternative implementations and plug them in with Spring configuration.
Quick Start
Start the server:
$ cd spring-cloud-config-server $ mvn spring-boot:run
The server is a Spring Boot application so you can build the jar file
and run that (java -jar …) or pull it down from a Maven
repository. Then try it out as a client:
$ curl localhost:8888/foo/development
{"name":"development","label":"master","propertySources":[
{"name":"https://github.com/scratches/config-repo/foo-development.properties","source":{"bar":"spam"}},
{"name":"https://github.com/scratches/config-repo/foo.properties","source":{"foo":"bar"}}
]}
The default strategy for locating property sources is to clone a git
repository (at "spring.cloud.config.server.uri") and use it to
initialize a mini SpringApplication. The mini-application’s
Environment is used to enumerate property sources and publish them
via a JSON endpoint. The service has resources in the form:
/{application}/{profile}[/{label}]
/{application}-{profile}.yml
/{label}/{application}-{profile}.yml
/{application}-{profile}.properties
/{label}/{application}-{profile}.properties
where the "application" is injected as the "spring.config.name" in the
SpringApplication (i.e. what is normally "application" in a regular
Spring Boot app), "profile" is an active profile (or comma-separated
list of properties), and "label" is an optional git label (defaults to
"master".) The YAML and properties forms are coalesced into a single
map, even if the origin of the values (reflected in the
"propertySources" of the "standard" form) has multiple sources.
Client Side Usage
To use these features in an application, just build it as a Spring
Boot application that depends on spring-cloud-config-client (e.g. see
the test cases for the config-client, or the sample app). The most
convenient way to add the dependency is via a Spring Boot starter
org.springframework.cloud:spring-cloud-starter. There is also a
parent pom and BOM (spring-cloud-starters) for Maven users and a
Spring IO version management properties file for Gradle and Spring CLI
users. Example Maven configuration:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.1.7.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starters</artifactId>
<version>1.0.0.BUILD-SNAPSHOT</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<!-- repositories also needed for snapshots and milestones -->
Then you can create a standard Spring Boot application, like this simple HTTP server:
@Configuration
@EnableAutoConfiguration
@RestController
public class Application {
@RequestMapping("/")
public String home() {
return "Hello World!";
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
When it runs it will pick up the external configuration from the
default local config server on port 8888 if it is running. To modify
the startup behaviour you can change the location of the config server
using bootstrap.properties (like application.properties but for
the bootstrap phase of an application context), e.g.
spring.cloud.config.uri: http://myconfigserver.com
The bootstrap properties will show up in the /env endpoint as a
high-priority property source, e.g.
$ curl localhost:8080/env
{
"profiles":[],
"configService:https://github.com/scratches/config-repo/bar.properties":{"foo":"bar"},
"servletContextInitParams":{},
"systemProperties":{...},
...
}
(a property source called "configService:<URL of remote repository>/<file name>" contains the property "foo" with value "bar" and is highest priority).
Spring Cloud Config Server
The Server provides an HTTP, resource-based API for external
configuration (name-value pairs, or equivalent YAML content). The
server is easily embeddable in a Spring Boot application using the
@EnableConfigServer annotation.
Security
You are free to secure your Config Server in any way that makes sense to you (from physical network security to OAuth2 bearer tokens), and Spring Security and Spring Boot make it easy to do pretty much anything.
To use the default Spring Boot configured HTTP Basic security, just
include Spring Security on the classpath (e.g. through
spring-boot-starter-security). The default is a username of "user"
and a randomly generated password, which isn’t going to be very useful
in practice, so we recommend you configure the password (via
security.user.password) and encrypt it (see below for instructions
on how to do that).
Encryption and Decryption
|
Important
|
Prerequisites: to use the encryption and decryption features you need the full-strength JCE installed in your JVM (it’s not there by default). You can download the "Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files" from Oracle, and follow instructions for installation (essentially replace the 2 policy files in the JRE lib/security directory with the ones that you downloaded). |
The server exposes /encrypt and /decrypt endpoints (on the
assumption that these will be secured and only accessed by authorized
agents). If the remote property sources contain encryted content
(values starting with {cipher}) they will be decrypted before
sending to clients over HTTP. The main advantage of this set up is
that the property values don’t have to be in plain text when they are
"at rest" (e.g. in a git repository). If a value cannot be decrypted
it is replaced with an empty string, largely to prevent cipher text
being used as a password in Spring Boot autconfigured HTTP basic.
If you are setting up a remote config repository for config client
applications it might contain an application.yml like this, for
instance:
spring:
datasource:
username: dbuser
password: {cipher}FKSAJDFGYOS8F7GLHAKERGFHLSAJ
You can safely push this plain text to a shared git repository and the secret password is protected.
If you are editing a remote config file you can use the Config Server
to encrypt values by POSTing to the /encrypt endpoint, e.g.
$ curl localhost:8888/encrypt -d mysecret 682bc583f4641835fa2db009355293665d2647dade3375c0ee201de2a49f7bda
The inverse operation is also available via /decrypt (provided the server is
configured with a symmetric key or a full key pair):
$ curl localhost:8888/decrypt -d 682bc583f4641835fa2db009355293665d2647dade3375c0ee201de2a49f7bda mysecret
Take the encypted value and add the {cipher} prefix before you put
it in the YAML or properties file, and before you commit and push it
to a remote, potentially insecure store.
The spring command line client (with Spring Cloud CLI extensions
installed) can also be used to encrypt and decrypt, e.g.
$ spring encrypt mysecret --key foo 682bc583f4641835fa2db009355293665d2647dade3375c0ee201de2a49f7bda $ spring decrypt --key foo 682bc583f4641835fa2db009355293665d2647dade3375c0ee201de2a49f7bda mysecret
To use a key in a file (e.g. an RSA public key for encyption) prepend the key value with "@" and provide the file path, e.g.
$ spring encrypt mysecret --key @${HOME}/.ssh/id_rsa.pub
AQAjPgt3eFZQXwt8tsHAVv/QHiY5sI2dRcR+...
Key Management
The Config Server can use a symmetric (shared) key or an asymmetric one (RSA key pair). The asymmetric choice is superior in terms of security, but it is often more convenient to use a symmetric key since it is just a single property value to configure.
To configure a symmetric key you just need to set encrypt.key to a
secret String (or use an enviroment variable ENCRYPT_KEY to keep it
out of plain text configuration files). You can also POST a key value
to the /key endpoint (but that won’t change any existing encrypted
values in remote repositories).
To configure an asymmetric key you can either set the key as a
PEM-encoded text value (in encrypt.key), or via a keystore (e.g. as
created by the keytool utility that comes with the JDK). The
keystore properties are encrypt.keyStore.* with * equal to
-
location(aResourcelocation), -
password(to unlock the keystore) and -
alias(to identify which key in the store is to be used).
The encryption is done with the public key, and a private key is needed for decryption. Thus in principle you can configure only the public key in the server if you only want to do encryption (and are prepared to decrypt the values yourself locally with the private key). In practice you might not want to do that because it spreads the key management process around all the clients, instead of concentrating it in the server. On the other hand it’s a useful option if your config server really is relatively insecure and only a handful of clients need the encrypted properties.
Creating a Key Store for Testing
To create a keystore for testing you can do something like this:
$ keytool -genkeypair -alias mytestkey -keyalg RSA \ -dname "CN=Web Server,OU=Unit,O=Organization,L=City,S=State,C=US" \ -keypass changeme -keystore server.jks -storepass letmein
Put the server.jks file in the classpath (for instance) and then in
your application.yml for the Config Server:
encrypt:
keyStore:
location: classpath:/server.jks
alias: mytestkey
password: letmein
Embedding the Config Server
The Config Server runs best as a standalone application, but if you
need to you can embed it in another application. Just use the
@EnableConfigServer annotation and (optionally) set
spring.cloud.config.server.prefix to a path prefix, e.g. "/config",
to serve the resources under a prefix. The prefix should start but not
end with a "/". It is applied to the @RequestMappings in the Config
Server (i.e. underneath the Spring Boot prefixes server.servletPath
and server.contextPath).
Spring Cloud Config Client
A Spring Boot application can take immediate advantage of the Spring
Config Server (or other external property sources provided by the
application developer), and it will also pick up some additional
useful features related to Environment change events.
Config First Bootstrap
This is the default behaviour for any application wich has the Spring
Cloud Config Client on the classpath. When a config client starts up
it binds to the Config Server (via the bootstrap configuration
property spring.cloud.config.uri) and initializes Spring
Environment with remote property sources.
The net result of this is that all client apps that want to consume
the Config Server need a bootstrap.yml (or an environment variable)
with the server address in spring.cloud.config.uri (defaults to
"http://localhost:8888").
Eureka First Bootstrap
If you are using Spring Cloud Netflix and Eureka Service Discovery, then you can have the Config Server register with Eureka if you want to, but in the default "Config First" mode, clients won’t be able to take advantage of the registration.
If you prefer to use Eureka to locate the Config Server, you can do
that by setting spring.cloud.config.discovery.enabled=true (default
"false"). The net result of that is that client apps all need a
bootstrap.yml (or an environment variable) with the Eureka server
address, e.g. in eureka.client.serviceUrl.defaultZone. The price
for using this option is an extra network round trip on start up to
locate the service registration. The benefit is that the Config Server
can change its co-ordinates, as long as Eureka is a fixed point.
Environment Changes
The application will listen for an EnvironmentChangedEvent and react
to the change in a couple of standard ways (additional
ApplicationListeners can be added as @Beans by the user in the
normal way). When an EnvironmentChangedEvent is observed it will
have a list of key values that have changed, and the application will
use those to:
-
Re-bind any
@ConfigurationPropertiesbeans in the context -
Set the logger levels for any properties in
logging.level.*
This covers a large class of refresh use cases, and you can verify the
changes by visiting the /configprops endpoint (normal Spring Boot
Actuator feature). For instance a DataSource can have its
maxPoolSize changed at runtime (the default DataSource created by
Spring Boot is an @ConfigurationProperties bean) and grow capacity
dynamically. It does not cover another large class of use cases, where
you need more control over the refresh, and where you need a
configuration change to be atomic over the whole
ApplicationContext. To address those concerns we have
@RefreshScope.
Refresh Scope
A Spring @Bean that is marked as @RefreshScope will get special
treatment when there is a configuration change. This addresses the
problem of stateful beans that only get their configuration injected
when they are initialized. For instance if a DataSource has open
connections when the database URL is changed via the Environment, we
probably want the holders of those connections to be able to complete
what they are doing. Then the next time someone borrows a connection
from the pool he gets one with the new URL.
Refresh scope beans are lazy proxies that initialize when they are used (i.e. when a method is called), and the scope acts as a cache of initialized values. To force a bean to re-initialize on the next method call you just need to invalidate its cache entry.
The RefreshScope is a bean in the context and it has a public method
refreshAll() to refresh all beans in the scope by clearing the
target cache. There is also a refresh(String) method to refresh an
individual bean by name. This functionality is exposed in the
/refresh endpoint (over HTTP or JMX).
Encryption and Decryption
The Config Client has an Environment pre-processor for decrypting
property values locally. It follows the same rules as the Config
Server, and has the same external configuration via encrypt.*. Thus
you can use encrypted values in the form {cipher}* and as long as
there is a valid key then they will be decrypted before the main
application context gets the Environment.
Endpoints
For a Spring Boot Actuator application there are some additional management endpoints:
-
POST to
/envto update theEnvironmentand rebind@ConfigurationPropertiesand log levels -
/refreshfor re-loading the boot strap context and refreshing the@RefreshScopebeans -
/restartfor closing theApplicationContextand restarting it (disabled by default) -
/pauseand/resumefor calling theLifecyclemethods (stop()andstart()on theApplicationContext)
Locating Remote Configuration Resources
The Config Service serves property sources from /{name}/{env}/{label}, where the default bindings in the
client app are
-
"name" =
${spring.application.name} -
"env" =
${spring.profiles.active}(actuallyEnvironment.getActiveProfiles()) -
"label" = "master"
All of them can be overridden by setting spring.cloud.config.*
(where * is "name", "env" or "label"). The "label" is useful for
rolling back to previous versions of configuration; with the default
Config Server implementation it can be a git label, branch name or
commit id.
The Bootstrap Application Context
The Config Client operates by creating a "bootstrap" application
context, which is a parent context for the main application. Out of
the box it is responsible for loading configuration properties from
the Config Server, and also decrypting properties in the local
external configuration files. The two contexts share an Environment
which is the source of external properties for any Spring
application. Bootstrap properties are added with high precedence, so
they cannot be overridden by local configuration.
The bootstrap context uses a different convention for locating
external configuration than the main application context, so instead
of application.yml (or .properties) you use bootstrap.yml,
keeping the external configuration for bootstrap and main context
nicely separate. Example:
spring:
application:
name: foo
cloud:
config:
uri: ${SPRING_CONFIG_URI:http://localhost:8888}
It is a good idea to set the spring.application.name (in
bootstrap.yml or application.yml) if your application needs any
application-specific configuration from the server.
You can disable the bootstrap process completely by setting
spring.cloud.bootstrap.enabled=false (e.g. in System properties).
Application Context Hierarchies
If you build an application context from SpringApplication or
SpringApplicationBuilder, then the Bootstrap context is added as a
parent to that context. It is a feature of Spring that child contexts
inherit property sources and profiles from their parent, so the "main"
application context will contain additional property sources, compared
to building the same context without Spring Cloud Config. The
additional property sources are:
-
"bootstrap": an optional
CompositePropertySourceappears with high priority if anyPropertySourceLocatorsare found in the Bootstrap context, and they have non-empty properties. An example would be properties from the Spring Cloud Config Server. See below for instructions on how to customize the contents of this property source. -
"applicationConfig: [classpath:bootstrap.yml]" (and friends if Spring profiles are active). If you have a
bootstrap.yml(or properties) then those properties are used to configure the Bootstrap context, and then they get added to the child context when its parent is set. They have lower precedence than theapplication.yml(or properties) and any other property sources that are added to the child as a normal part of the process of creating a Spring Boot application. See below for instructions on how to customize the contents of these property sources.
Because of the ordering rules of property sources the "bootstrap"
entries take precedence, but note that these do not contain any data
from bootstrap.yml, which has very low precedence, but can be used
to set defaults.
You can extend the context hierarchy by simply setting the parent
context of any ApplicationContext you create, e.g. using its own
interface, or with the SpringApplicationBuilder convenience methods
(parent(), child() and sibling()). The bootstrap context will be
the parent of the most senior ancestor that you create yourself.
Every context in the hierarchy will have its own "bootstrap" property
source (possibly empty) to avoid promoting values inadvertently from
parents down to their descendants. Every context in the hierarchy can
also (in principle) have a different spring.application.name and
hence a different remote property source if there is a Config
Server. Normal Spring application context behaviour rules apply to
property resolution: properties from a child context override those in
the parent, by name and also by property source name (if the child has
a property source with the same name as the parent, the one from the
parent is not included in the child).
Note that the SpringApplicationBuilder allows you to share an
Environment amongst the whole hierarchy, but that is not the
default. Thus, sibling contexts in particular do not need to have the
same profiles or property sources, even though they will share common
things with their parent.
Changing the Location of Bootstrap Properties
The bootstrap.yml (or .properties) location can be specified using
`spring.cloud.bootstrap.name (default "bootstrap") or
spring.cloud.bootstrap.location (default empty), e.g. in System
properties. Those properties behave like the spring.config.*
variants with the same name, in fact they are used to set up the
bootstrap ApplicationContext by setting those properties in its
Environment. If there is an active profile (from
spring.profiles.active or through the Environment API in the
context you are building) then properties in that profile will be
loaded as well, just like in a regular Spring Boot app, e.g. from
bootstrap-development.properties for a "development" profile.
Customizing the Bootstrap Configuration
The bootstrap context can be trained to do anything you like by adding
entries to /META-INF/spring.factories under the key
org.springframework.cloud.bootstrap.BootstrapConfiguration. This is
a comma-separated list of Spring @Configuration classes which will
be used to create the context. Any beans that you want to be available
to the main application context for autowiring can be created here,
and also there is a special contract for @Beans of type
ApplicationContextInitializer.
The bootstrap process ends by injecting initializers into the main
SpringApplication instance (i.e. the normal Spring Boot startup
sequence, whether it is running as a standalone app or deployed in an
application server). First a bootstrap context is created from the
classes found in spring.factories and then all @Beans of type
ApplicationContextInitializer are added to the main
SpringApplication before it is started.
Customizing the Bootstrap Property Sources
The default property source for external configuration added by the
bootstrap process is the Config Server, but you can add additional
sources by adding beans of type PropertySourceLocator to the
bootstrap context (via spring.factories). You could use this to
insert additional properties from a different server, or from a
database, for instance.
As an example, consider the following trivial custom locator:
@Configuration
public class CustomPropertySourceLocator implements PropertySourceLocator {
@Override
public PropertySource<?> locate(Environment environment) {
return new MapPropertySource("customProperty",
Collections.<String, Object>singletonMap("property.from.sample.custom.source", "worked as intended"));
}
}
The Environment that is passed in is the one for the
ApplicationContext about to be created, i.e. the one that we are
supplying additional property sources for. It will already have its
normal Spring Boot-provided property sources, so you can use those to
locate a property source specific to this Environment (e.g. by
keying it on the spring.application.name, as is done in the default
Config Server property source locator).
If you create a jar with this class in it and then add a
META-INF/spring.factories containing:
org.springframework.cloud.bootstrap.BootstrapConfiguration=sample.custom.CustomPropertySourceLocator
then the "customProperty" PropertySource will show up in any
application that includes that jar on its classpath.
Security
If you use HTTP Basic security on the server then clients just need to know the password (and username if it isn’t the default). You can do that via the config server URI, or via separate username and password properties, e.g.
spring:
cloud:
config:
uri: https://user:secret@myconfig.mycompany.com
or
spring:
cloud:
config:
uri: https://myconfig.mycompany.com
username: user
password: secret
The spring.cloud.config.password and spring.cloud.config.username
values override anything that is provided in the URI.
If you deploy your apps on Cloud Foundry then the best way to provide the password is through service credentials, e.g. in the URI, since then it doesn’t even need to be in a config file. An example which works locally and for a user-provided service on Cloud Foundry named "configserver":
spring:
cloud:
config:
uri: ${vcap.services.configserver.credentials.uri:http://user:password@localhost:8888}
If you use another form of security you might need to provide a
RestTemplate to the ConfigServicePropertySourceLocator (e.g. by
grabbing it in the bootstrap context and injecting one).
Spring Cloud Netflix
Service Discovery: Eureka Clients
Service Discovery is one of the key tenets of a microservice based architecture. Trying to hand configure each client or some form of convention can be very difficult to do and can be very brittle. Eureka is the Netflix Service Discovery Server and Client. The server can be configured and deployed to be highly available, with each server replicating state about the registered services to the others.
When clients register with Eureka, they provide eureka with meta-data about themselves such as host and port, health indicator URL, home page etc. Eureka receives heartbeat messages from each instance belonging to a service. If the heartbeat fails over a configurable timetable, the instance is normally removed from Eureka.
Example eureka client:
@Configuration
@ComponentScan
@EnableAutoConfiguration
@EnableEurekaClient
@RestController
public class Application {
@RequestMapping("/")
public String home() {
return "Hello world";
}
public static void main(String[] args) {
new SpringApplicationBuilder(Application.class).web(true).run(args);
}
}
(i.e. utterly normal Spring Boot app). Configuration is required to locate the Eureka server. Example:
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
where "defaultZone" is a magic string fallback value that provides the service URL for any client that doesn’t express a preference (i.e. it’s a useful default).
The default application name (service ID), virtual host and non-secure
port, taken from the Environment, are ${spring.application.name},
${spring.application.name} and ${server.port} respectively.
@EnableEurekaClient makes the app into both a Eureka "instance"
(i.e. it registers itself) and a "client" (i.e. it can query the
registry to locate other services). The instance behaviour is driven
by eureka.instance.* configuration keys, but the defaults will be
fine if you ensure that your application has a
spring.application.name (this is the default for the Eureka service
ID, or VIP).
See EurekaInstanceConfigBean and EurekaClientConfigBean for more details of the configurable options.
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
service is not available for discovery by clients until the instance,
the server and the client all have the same metadata in their local
cache (so it could take 3 hearbeats). You can change the period using
eureka.instance.leaseRenewalIntervalInSeconds and this will speed up
the process of getting clients connected to other services. In
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:
@Configuration
@EnableAutoConfiguration
@EnableEurekaServer
public class Application {
public static void main(String[] args) {
new SpringApplicationBuilder(Application.class).web(true).run(args);
}
}
The server has a home page with a UI, and HTTP API endpoints per the
normal Eureka functionality under /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 Boot build tools, but to avoid problems with classpath scanning in Jersey 1.x you have to tell the build plugins to unpack the jars that contain JAX-RS resources, e.g. (for Maven) pom.xml
or with Gradle build.gradle
|
High Availability, Zones and Regions
The Eureka server does not have a backend store, but the service instances in the registry all have to send heartbeats to keep their resistrations up to date (so this can be done in memory). Clients also have an in-memory cache of eureka registrations (so they don’t have to go to the registry for every single request to a service).
By default every Eureka server is also a Eureka client and requires (at least one) service URL to locate a peer. If you don’t provide it 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 failure, as long as there is some sort of monitor or elastic runtime keeping it alive (e.g. Cloud Foundry). In standalone mode, you might prefer to switch off the client side behaviour, so it doesn’t keep trying and failing to reach its peers. Example:
server:
port: 8761
eureka:
instance:
hostname: localhost
client:
registerWithEureka: false
fetchRegistry: false
serviceUrl:
defaultZone: http://${eureka.instance.hostname}:${server.port}/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
fact, this is the default behaviour, so all you need to do to make it
work is add a valid serviceUrl to a peer, e.g.
---
spring:
profiles: peer1
eureka:
instance:
hostname: peer1
client:
serviceUrl:
defaultZone: http://peer2/eureka/
---
spring:
profiles: peer2
eureka:
instance:
hostname: peer2
client:
serviceUrl:
defaultZone: http://peer1/eureka/
In this example we have a YAML file that can be used to run the same
server on 2 hosts (peer1 and peer2), by running it in different
Spring profiles. You could use this configuration to test the peer
awareness on a single host (there’s not much value in doing that in
production) by manipulating /etc/hosts to resolve the host names. In
fact, the eureka.instance.hostname is not needed if you are running
on a machine that knows its own hostname (it is looked up using
java.net.InetAddress by default).
You can add multiple peers to a system, and as long as they are all connected to each other by at least one edge, they will synchronize 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.
A service failure in the lower level of services can cause cascading failure all the way up to the user. When calls to a particular service reach a certain threshold (20 failures in 5 seconds is the default in Hystrix), the circuit opens and the call is not made. In cases of error and an open circuit a fallback can be provided by the developer.
Having an open circuit stops cascading failures and allows overwhelmed or failing services time to heal. The fallback can be another Hystrix protected call, static data or a sane empty value. Fallbacks may be chained so the first fallback makes some other business call which in turn falls back to static data.
Example boot app:
@Configuration
@EnableAutoConfiguration
@EnableHystrix
public class Application {
public static void main(String[] args) {
new SpringApplicationBuilder(Application.class).web(true).run(args);
}
}
@Component
public class StoreIntegration {
@HystrixCommand(fallbackMethod = "defaultStores")
public Object getStores(Map<String, Object> parameters) {
//do stuff that might fail
}
public Object defaultStores(Map<String, Object> parameters) {
return /* something useful */;
}
}
The @HystrixCommand is provided by a Netflix contrib library called
"javanica". Spring Cloud automatically wraps Spring beans with that
annotation in a proxy that is connected to the Hystrix circuit
breaker. The circuit breaker calculates when to open and close the
circuit, and what to do in case of a failure.
The state of the connected circuit breakers are also exposed in the
/health endpoint of the calling application.
{
"hystrix": {
"openCircuitBreakers": [
"StoreIntegration::getStoresByLocationLink"
],
"status": "CIRCUIT_OPEN"
},
"status": "UP"
}
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.
turbine.appConfig is a list of eureka serviceId’s that turbine will use to lookup instances. turbine.aggregator.clusterConfig is used to group instances together. This comes from the eureka InstanceInfo. The clusterName is a SPEL expression evaluated against the InstanceInfo. The default clusterNameExpression is appName. The turbine stream is then used in the Hystrix dashboard using a url that looks like: http://my.turbine.sever:8080/turbine.stream?cluster=CUSTOMERS
The cluster parameter must match an entry in turbine.aggregator.clusterConfig.
turbine:
aggregator:
clusterConfig: CUSTOMERS
appConfig: customers
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.
Example spring boot app
@Configuration
@ComponentScan
@EnableAutoConfiguration
@EnableEurekaClient
public class Application extends FeignConfigurer {
@Bean
public StoreClient storeClient() {
//loadBalance plugs Feign into ribbon. feign() works without load balancing.
return loadBalance(StoreClient.class, "http://stores");
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
public interface StoreClient {
@RequestMapping(method = RequestMethod.GET, value = "/stores")
Stores getStores();
@RequestMapping(method = RequestMethod.POST, value = "/stores/{storeId}", consumes = "application/json")
Store update(@PathParameter("storeId") Long storeId, Store store);
}
Client Side Load Balancer: Ribbon
Usage of LoadBalancerClient directly:
public class MyClass {
@Autowired
private LoadBalancerClient loadBalancer;
public void doStuff() {
ServiceInstance instance = loadBalancer.choose("stores");
URI storesUri = URI.create(String.format("http://%s:%s", instance.getHost(), instance.getPort()));
// ... do something with the URI
}
}
Indirect usage via RestTemplate.
public class MyClass {
@Autowired
private RestTemplate restTemplate;
public String doOtherStuff() {
String results = restTemplate.getForObject("http://stores/stores", String.class);
return results;
}
}
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.
class ArchaiusTest {
DynamicStringProperty myprop = DynamicPropertyFactory
.getInstance()
.getStringProperty("my.prop");
void doSomething() {
OtherClass.someMethod(myprop.get());
}
}
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.
Netflix uses Zuul for the following:
-
Authentication
-
Insights
-
Stress Testing
-
Canary Testing
-
Dynamic Routing
-
Service Migration
-
Load Shedding
-
Security
-
Static Response handling
-
Active/Active traffic management
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. Configuration rules look like the following:
zuul.proxy.route.users: /users
This means that http calls to /proxy/users to the users service. This proxy configuration is useful for services that host a user interface to proxy to the backend services it requires.
Spring Cloud Cluster
Spring Platform Bus
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.
spring:
rabbitmq:
host: mybroker.com
port: 5672
username: user
password: secret
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
Installation
To install, make sure you have Spring Boot CLI (1.1.x with x>=5):
$ spring version Spring CLI v1.1.8.RELEASE
E.g. for GVM users
$ gvm install springboot 1.1.8.RELEASE
$ gvm use springboot 1.1.8.RELEASE
then get the install command plugin (backported from Boot 1.2.0):
$ wget http://dl.bintray.com/dsyer/generic/install-0.0.2.jar
install it in the Spring Boot CLI, e.g. with GVM (MacOS users that rely on brew might have to find the /lib directory by scanning brew info springboot):
$ cp install-0.0.2.jar ~/.gvm/springboot/1.1.8.RELEASE/lib
and finally install the Spring Cloud plugin:
$ mvn install
$ spring install org.springframework.cloud:spring-cloud-cli:1.0.0.BUILD-SNAPSHOT
Spring Cloud Security
Quickstart
OAuth Single Sign On
Here’s a Spring Cloud "Hello World" app with HTTP Basic authentication and a single user account:
@Grab('spring-boot-starter-security')
@Controller
class Application {
@RequestMapping('/')
String home() {
'Hello World'
}
}
You can run it with spring run app.groovy and watch the logs for the password (username is "user"). So far this is just the default for a Spring Boot app.
Here’s a Spring Cloud app with OAuth2 SSO:
@Controller
@EnableOAuth2Sso
class Application {
@RequestMapping('/')
String home() {
'Hello World'
}
}
Spot the difference? This app will actually behave exactly the same as the previous one, because it doesn’t know it’s OAuth2 credentals yet.
You can register an app in github quite easily, so try that if you want a production app on your own domain. If you are happy to test on localhost:8080, then set up these properties in your application configuration:
oauth2:
client:
clientId: bd1c0a783ccdd1c9b9e4
clientSecret: 1a9030fbca47a5b2c28e92f19050bb77824b5ad1
tokenUri: https://github.com/login/oauth/access_token
authorizationUri: https://github.com/login/oauth/authorize
authenticationScheme: form
resource:
userInfoUri: https://api.github.com/user
preferTokenInfo: false
run the app above and it will redirect to github for authorization. If you are already signed into github you won’t even notice that it has 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).
OAuth Protected Resource
You want to protect an API resource with an OAuth2 token? Here’s a simple example (paired with the client above):
@Grab('spring-cloud-starter-security')
@RestController
@EnableOAuth2Resource
class Application {
@RequestMapping('/'
def home() {
[message: 'Hello World']
}
}
and
oauth2:
resource:
userInfoUri: https://api.github.com/user
preferTokenInfo: false
Token Relay
If your app has a
Spring
Cloud Zuul embedded reverse proxy (using @EnableZuulProxy) then you
can ask it to forward OAuth2 access tokens downstream to the services
it is proxying. Thus the SSO app above can be enhanced simply like this:
@Controller
@EnableOAuth2Sso
@EnableZuulProxy
class Application {
@RequestMapping('/'
String home() {
'Hello World'
}
}
and it will (in addition to loggin the user in and grabbing a token)
pass the authentication token downstream to the /proxy/*
services. If those services are implemented with
@EnableOAuth2Resource then they will get a valid token in the
correct header.
How does it work? The @EnableOAuth2Sso annotation pulls in
spring-cloud-starter-security (which you could do manually in a
traditional app), and that has some autoconfiguration for a
ZuulFilter, which itself is activated because Zuul is on the
classpath (via @EnableZuulProxy). The
filter
just extracts an access token from the currently authenticated user,
and puts it in a request header for the downstream requests.