GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
GeezerVison is showing cloud.spring.io (truncated) — Spring Cloud Spring CloudTable of Contents
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. Version: Brixton.BUILD-SNAPSHOT FeaturesSpring Cloud focuses on providing good out of box experience for typical use cases and extensibility mechanism to cover others.
Cloud Native ApplicationsCloud Native is a style of application development that encourages easy adoption of best practices in the areas of continuous delivery and value-driven development. A related discipline is that of building 12-factor Apps in which development practices are aligned with delivery and operations goals, for instance by using declarative programming and management and monitoring. Spring Cloud facilitates these styles of development in a number of specific ways and the starting point is a set of features that all components in a distributed system either need or need easy access to when required. Many of those features are covered by Spring Boot, which we build on in Spring Cloud. Some more are delivered by Spring Cloud as two libraries: Spring Cloud Context and Spring Cloud Commons. Spring Cloud Context provides utilities and special services for the If you are getting an exception due to "Illegal key size" and you are using Sun’s JDK, you need to install the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files. See the following links for more information: Extract files into JDK/jre/lib/security folder (whichever version of JRE/JDK x64/x86 you are using).
Spring Cloud Context: Application Context ServicesSpring Boot has an opinionated view of how to build an application with Spring: for instance it has conventional locations for common configuration file, and endpoints for common management and monitoring tasks. Spring Cloud builds on top of that and adds a few features that probably all components in a system would use or occasionally need. The Bootstrap Application ContextA Spring Cloud application operates by creating a "bootstrap"
context, which is a parent context for the main application. Out of
the box it is responsible for loading configuration properties from
the external sources, and also decrypting properties in the local
external configuration files. The two contexts share an The bootstrap context uses a different convention for locating
external configuration than the main application context, so instead
of bootstrap.yml
spring:
application:
name: foo
cloud:
config:
uri: ${SPRING_CONFIG_URI:http://localhost:8888}
It is a good idea to set the You can disable the bootstrap process completely by setting
Application Context HierarchiesIf you build an application context from
Because of the ordering rules of property sources the "bootstrap"
entries take precedence, but note that these do not contain any data
from You can extend the context hierarchy by simply setting the parent
context of any Note that the Changing the Location of Bootstrap PropertiesThe Overriding the Values of Remote PropertiesThe property sources that are added to you application by the
bootstrap context are often "remote" (e.g. from a Config Server), and
by default they cannot be overridden locally, except on the command
line. If you want to allow your applications to override the remote
properties with their own System properties or config files, the
remote property source has to grant it permission by setting
Customizing the Bootstrap ConfigurationThe bootstrap context can be trained to do anything you like by adding
entries to
The bootstrap process ends by injecting initializers into the main
Customizing the Bootstrap Property SourcesThe 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 As an example, consider the following trivial custom locator:
The If you create a jar with this class in it and then add a
org.springframework.cloud.bootstrap.BootstrapConfiguration=sample.custom.CustomPropertySourceLocator then the "customProperty" Environment ChangesThe application will listen for an
Note that the Config Client does not by default poll for changes in
the The Refresh ScopeA Spring 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
Encryption and DecryptionSpring Cloud has an If you are getting an exception due to "Illegal key size" and you are using Sun’s JDK, you need to install the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files. See the following links for more information: Extract files into JDK/jre/lib/security folder (whichever version of JRE/JDK x64/x86 you are using). EndpointsFor a Spring Boot Actuator application there are some additional management endpoints:
Spring Cloud Commons: Common AbstractionsPatterns such as service discovery, load balancing and circuit breakers lend themselves to a common abstraction layer that can be consumed by all Spring Cloud clients, independent of the implementation (e.g. discovery via Eureka or Consul). @EnableDiscoveryClientCommons provides the By default, implementations of ServiceRegistryCommons now provides a Service Registry Actuator EndpointA Spring RestTemplate as a Load Balancer Client
The URI needs to use a virtual host name (ie. service name, not a host name).
The Ribbon client is used to create a full physical address. See
RibbonAutoConfiguration
for details of how the Retrying Failed RequestsA load balanced
Multiple RestTemplate objectsIf you want a
Ignore Network InterfacesSometimes it is useful to ignore certain named network interfaces so they can be excluded from Service Discovery registration (eg. running in a Docker container). A list of regular expressions can be set that will cause the desired network interfaces to be ignored. The following configuration will ignore the "docker0" interface and all interfaces that start with "veth". application.yml
spring:
cloud:
inetutils:
ignoredInterfaces:
- docker0
- veth.*
You can also force to use only specified network addresses using list of regular expressions: application.yml
spring:
cloud:
inetutils:
preferredNetworks:
- 192.168
- 10.0
You can also force to use only site local addresses. See Inet4Address.html.isSiteLocalAddress() for more details what is site local address. application.yml
spring:
cloud:
inetutils:
useOnlySiteLocalInterfaces: true
Spring Cloud Config
Spring Cloud Config provides server and client-side support for externalized configuration in a distributed system. With the Config Server you have a central place to manage external properties for applications across all environments. The concepts on both client and server map identically to the Spring
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 StartStart the server: $ cd spring-cloud-config-server $ ../mvnw spring-boot:run The server is a Spring Boot application so you can run it from your
IDE instead if you prefer (the main class is
$ 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 The HTTP 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 Cloud Config Server pulls configuration for remote clients from a git repository (which must be provided):
Client Side UsageTo 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
pom.xml
Then you can create a standard Spring Boot application, like this simple HTTP server: @SpringBootApplication
@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 spring.cloud.config.uri: http://myconfigserver.com The bootstrap properties will show up in the $ curl localhost:8080/env
{
"profiles":[],
"configService:https://github.com/spring-cloud-samples/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 ServerThe 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
ConfigServer.java
Like all Spring Boot apps it runs on port 8080 by default, but you
can switch it to the conventional port 8888 in various ways. The
easiest, which also sets a default configuration repository,
is by launching it with application.properties
where
Environment RepositoryWhere do you want to store the configuration data for the Config
Server? The strategy that governs this behaviour is the
Repository implementations generally behave just like a Spring Boot
application loading configuration files from a "spring.config.name"
equal to the Example: a client application has this bootstrap configuration: bootstrap.yml
(as usual with a Spring Boot application, these properties could also be set as environment variables or command line arguments). If the repository is file-based, the server will create an
Git BackendThe default implementation of This repository implementation maps the Placeholders in Git URISpring Cloud Config Server supports a git repository URL with
placeholders for the
or a "one repo per profile" policy using a similar pattern but with
Pattern Matching and Multiple RepositoriesThere is also support for more complex requirements with pattern
matching on the application and profile name. The pattern format is a
comma-separated list of
If
The
Every repository can also optionally store config files in
sub-directories, and patterns to search for those directories can be
specified as
In this example the server searches for config files in the top level and in the "foo/" sub-directory and also any sub-directory whose name begins with "bar". By default the server clones remote repositories when configuration is first requested. The server can be configured to clone the repositories at startup. For example at the top level:
In this example the server clones team-a’s config-repo on startup before it accepts any requests. All other repositories will not be cloned until configuration from the repository is requested. To use HTTP basic authentication on the remote repository add the "username" and "password" properties separately (not in the URL), e.g.
If you don’t use HTTPS and user credentials, SSH should also work out
of the box when you store keys in the default directories (
Placeholders in Git Search PathsSpring Cloud Config Server also supports a search path with
placeholders for the
searches the repository for files in the same name as the directory (as well as the top level). Wildcards are also valid in a search path with placeholders (any matching directory is included in the search). Version Control Backend Filesystem Use
File System BackendThere is also a "native" profile in the Config Server that doesn’t use Git, but just loads the config files from the local classpath or file system (any static URL you want to point to with "spring.cloud.config.server.native.searchLocations"). To use the native profile just launch the Config Server with "spring.profiles.active=native".
The search locations can contain placeholders for If you don’t use placeholders in the search locations, this repository
also appends the Sharing Configuration With All ApplicationsWith file-based (i.e. git, svn and native) repositories, resources
with file names in The #_property_overrides[property overrides] feature can also be used for setting global defaults, and with placeholders applications are allowed to override them locally.
Property OverridesThe Config Server has an "overrides" feature that allows the operator
to provide configuration properties to all applications that cannot be
accidentally changed by the application using the normal Spring Boot
hooks. To declare overrides just add a map of name-value pairs to
will cause all applications that are config clients to read
You can change the priority of all overrides in the client to be more
like default values, allowing applications to supply their own values
in environment variables or System properties, by setting the flag
Health IndicatorConfig Server comes with a Health Indicator that checks if the configured
You can configure the Health Indicator to check more applications along with custom profiles and custom labels, e.g.
You can disable the Health Indicator by setting SecurityYou 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
Encryption and Decryption
If the remote property sources contain encrypted content (values
starting with If you are setting up a remote config repository for config client
applications it might contain an application.yml
Encrypted values in a .properties file must not be wrapped in quotes, otherwise the value will not be decrypted: application.properties
spring.datasource.username: dbuser
spring.datasource.password: {cipher}FKSAJDFGYOS8F7GLHAKERGFHLSAJ
You can safely push this plain text to a shared git repository and the secret password is protected. The server also exposes $ curl localhost:8888/encrypt -d mysecret 682bc583f4641835fa2db009355293665d2647dade3375c0ee201de2a49f7bda The inverse operation is also available via $ curl localhost:8888/decrypt -d 682bc583f4641835fa2db009355293665d2647dade3375c0ee201de2a49f7bda mysecret
Take the encrypted value and add the The
The $ 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 encryption) prepend the key value with "@" and provide the file path, e.g. $ spring encrypt mysecret --key @${HOME}/.ssh/id_rsa.pub
AQAjPgt3eFZQXwt8tsHAVv/QHiY5sI2dRcR+...
The key argument is mandatory (despite having a Key ManagementThe 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 To configure an asymmetric key you can either set the key as a
PEM-encoded text value (in
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 TestingTo 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
Using Multiple Keys and Key RotationIn addition to the
the locator will look for a key named "testkey". A secret can also be
supplied via a Key rotation is hardly ever necessary on cryptographic grounds if the
keys are only being used to encrypt a few bytes of configuration data
(i.e. they are not being used elsewhere), but occasionally you might
need to change the keys if there is a security breach for instance. In
that case all the clients would need to change their source config
files (e.g. in git) and use a new
Serving Encrypted PropertiesSometimes you want the clients to decrypt the configuration locally,
instead of doing it in the server. In that case you can still have
/encrypt and /decrypt endpoints (if you provide the Serving Alternative FormatsThe default JSON format from the environment endpoints is perfect for
consumption by Spring applications because it maps directly onto the
The YAML and properties representations have an additional flag
(provided as a boolean query parameter
Serving Plain TextInstead of using the After a resource is located, placeholders in the normal format
( application.yml nginx.conf where server {
listen 80;
server_name ${nginx.server.name};
}
and
then the server {
listen 80;
server_name example.com;
}
and server {
listen 80;
server_name develop.com;
}
Embedding the Config ServerThe Config Server runs best as a standalone application, but if you
need to you can embed it in another application. Just use the
To change the location of the server endpoints you can (optionally)
set If you want to read the configuration for an application directly from
the backend repository (instead of from the config server) that’s
basically an embedded config server with no endpoints. You can switch
off the endpoints entirely if you don’t use the Push Notifications and Spring Cloud BusMany source code repository providers (like Github, Gitlab or Bitbucket
for instance) will notify you of changes in a repository through a
webhook. You can configure the webhook via the provider’s user
interface as a URL and a set of events in which you are
interested. For instance
Github
will POST to the webhook with a JSON body containing a list of
commits, and a header "X-Github-Event" equal to "push". If you add a
dependency on the When the webhook is activated the Config Server will send a
The default configuration works out of the box with Github, Gitlab or
Bitbucket. In addition to the JSON notifications from Github, Gitlab
or Bitbucket you can trigger a change notification by POSTing to
"/monitor" with a form-encoded body parameters
Spring Cloud Config ClientA 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 Config First BootstrapThis is the default behaviour for any application which 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 The net result of this is that all client apps that want to consume
the Config Server need a Discovery First BootstrapIf you are using a `DiscoveryClient implementation, such as Spring Cloud Netflix and Eureka Service Discovery or Spring Cloud Consul (Spring Cloud Zookeeper does not support this yet), then you can have the Config Server register with the Discovery Service 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 The discovery client implementations all support some kind of metadata
map (e.g. for Eureka we have bootstrap.yml
Config Client Fail FastIn some cases, it may be desirable to fail startup of a service if
it cannot connect to the Config Server. If this is the desired
behavior, set the bootstrap configuration property
Config Client RetryIf you expect that the config server may occasionally be unavailable when
your app starts, you can ask it to keep trying after a failure. First you need
to set
Locating Remote Configuration ResourcesThe Config Service serves property sources from
All of them can be overridden by setting SecurityIf 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. bootstrap.yml
or bootstrap.yml
The 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": bootstrap.yml
If you use another form of security you might need to provide a
Spring Cloud Netflix
This project provides Netflix OSS integrations for Spring Boot apps through autoconfiguration
and binding to the Spring Environment and other Spring programming model idioms. With a few
simple annotations you can quickly enable and configure the common patterns inside your
application and build large distributed systems with battle-tested Netflix components. The
patterns provided include Service Discovery (Eureka), Circuit Breaker (Hystrix),
Intelligent Routing (Zuul) and Client Side Load Balancing (Ribbon).
Service Discovery: Eureka ClientsService 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. Registering with EurekaWhen a client registers with Eureka, it provides meta-data about itself 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 the registry. Example eureka client:
(i.e. utterly normal Spring Boot app). In this example we use
application.yml
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
See EurekaInstanceConfigBean and EurekaClientConfigBean for more details of the configurable options. Authenticating with the Eureka ServerHTTP basic authentication will be automatically added to your eureka
client if one of the
Status Page and Health IndicatorThe status page and health indicators for a Eureka instance default to
"/info" and "/health" respectively, which are the default locations of
useful endpoints in a Spring Boot Actuator application. You need to
change these, even for an Actuator application if you use a
non-default context path or servlet path
(e.g. application.yml
eureka:
instance:
statusPageUrlPath: ${management.context-path}/info
healthCheckUrlPath: ${management.context-path}/health
These links show up in the metadata that is consumed by clients, and used in some scenarios to decide whether to send requests to your application, so it’s helpful if they are accurate. Registering a Secure ApplicationIf your app wants to be contacted over HTTPS you can set two flags in
the Because of the way Eureka works internally, it will still publish a non-secure URL for status and home page unless you also override those explicitly. You can use placeholders to configure the eureka instance urls, e.g. application.yml
eureka:
instance:
statusPageUrl: https://${eureka.hostname}/info
healthCheckUrl: https://${eureka.hostname}/health
homePageUrl: https://${eureka.hostname}/
(Note that
Eureka’s Health ChecksBy default, Eureka uses the client heartbeat to determine if a client is up. Unless specified otherwise the Discovery Client will not propagate the current health check status of the application per the Spring Boot Actuator. Which means that after successful registration Eureka will always announce that the application is in 'UP' state. This behaviour can be altered by enabling Eureka health checks, which results in propagating application status to Eureka. As a consequence every other application won’t be sending traffic to application in state other then 'UP'. application.yml
eureka:
client:
healthcheck:
enabled: true
If you require more control over the health checks, you may consider
implementing your own Eureka Metadata for Instances and ClientsIt’s worth spending a bit of time understanding how the Eureka metadata works, so you can use it in a way that makes sense in your platform. There is standard metadata for things like hostname, IP address, port numbers, status page and health check. These are published in the service registry and used by clients to contact the services in a straightforward way. Additional metadata can be added to the instance registration in the Using Eureka on CloudfoundryCloudfoundry has a global router so that all instances of the same app have the same hostname (it’s the same in other PaaS solutions with a similar architecture). This isn’t necessarily a barrier to using Eureka, but if you use the router (recommended, or even mandatory depending on the way your platform was set up), you need to explicitly set the hostname and port numbers (secure or non-secure) so that they use the router. You might also want to use instance metadata so you can distinguish between the instances on the client (e.g. in a custom load balancer). By default, the application.yml
eureka:
instance:
hostname: ${vcap.application.uris[0]}
nonSecurePort: 80
Depending on the way the security rules are set up in your Cloudfoundry instance, you might be able to register and use the IP address of the host VM for direct service-to-service calls. This feature is not (yet) available on Pivotal Web Services (PWS). Using Eureka on AWSIf the application is planned to be deployed to an AWS cloud, then the Eureka instance will have to be configured to be Amazon aware and this can be done by customizing the EurekaInstanceConfigBean the following way:
Changing the Eureka Instance IDA vanilla Netflix Eureka instance is registered with an ID that is equal to its host name (i.e. only one service per host). Spring Cloud Eureka provides a sensible default that looks like this: Using Spring Cloud you can override this by providing a unique identifier in application.yml
eureka:
instance:
instanceId: ${spring.application.name}:${spring.application.instance_id:${random.value}}
With this metadata, and multiple service instances deployed on
localhost, the random value will kick in there to make the instance
unique. In Cloudfoundry the Using the EurekaClientOnce you have an app that is @Autowired
private EurekaClient discoveryClient;
public String serviceUrl() {
InstanceInfo instance = discoveryClient.getNextServerFromEureka("STORES", false);
return instance.getHomePageUrl();
}
Alternatives to the native Netflix EurekaClientYou don’t have to use the raw Netflix You can also use the @Autowired
private DiscoveryClient discoveryClient;
public String serviceUrl() {
List<ServiceInstance> list = discoveryClient.getInstances("STORES");
if (list != null && list.size() > 0 ) {
return list.get(0).getUri();
}
return null;
}
Why is it so Slow to Register a Service?Being an instance also involves a periodic heartbeat to the registry
(via the client’s Service Discovery: Eureka ServerExample eureka server (e.g. using spring-cloud-starter-eureka-server to set up the classpath):
The server has a home page with a UI, and HTTP API endpoints per the
normal Eureka functionality under Eureka background reading: see flux capacitor and google group discussion.
High Availability, Zones and RegionsThe Eureka server does not have a backend store, but the service instances in the registry all have to send heartbeats to keep their registrations 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. See also below for details of Ribbon support on the client side for Zones and Regions. Standalone ModeThe 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: application.yml (Standalone Eureka Server)
server:
port: 8761
eureka:
instance:
hostname: localhost
client:
registerWithEureka: false
fetchRegistry: false
serviceUrl:
defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
Notice that the Peer AwarenessEureka 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 application.yml (Two Peer Aware Eureka Servers)
---
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 You can add multiple peers to a system, and as long as they are all directly connected to each other, they will synchronize the registrations amongst themselves. application.yml (Three Peer Aware Eureka Servers)
eureka:
client:
serviceUrl:
defaultZone: http://peer1/eureka/,http://peer2/eureka/,http://peer3/eureka/
---
spring:
profiles: peer1
eureka:
instance:
hostname: peer1
---
spring:
profiles: peer2
eureka:
instance:
hostname: peer2
---
spring:
profiles: peer3
eureka:
instance:
hostname: peer3
Prefer IP AddressIn some cases, it is preferable for Eureka to advertise the IP Adresses
of services rather than the hostname. Set Circuit Breaker: Hystrix ClientsNetflix 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.
Figure 1. Microservice Graph
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.
Figure 2. Hystrix fallback prevents cascading failures
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: @SpringBootApplication
@EnableCircuitBreaker
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 To configure the Propagating the Security Context or using Spring ScopesIf you want some thread local context to propagate into a
The same thing applies if you are using Health IndicatorThe state of the connected circuit breakers are also exposed in the
Hystrix Metrics StreamTo enable the Hystrix metrics stream include a dependency on
Circuit Breaker: Hystrix DashboardOne 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.
Figure 3. Hystrix Dashboard
To run the Hystrix Dashboard annotate your Spring Boot main class with TurbineLooking 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 The configuration key turbine:
aggregator:
clusterConfig: CUSTOMERS
appConfig: customers
The turbine:
aggregator:
clusterConfig: SYSTEM,USER
appConfig: customers,stores,ui,admin
clusterNameExpression: metadata['cluster']
In this case, the cluster name from 4 services is pulled from their metadata map, and is expected to have values that include "SYSTEM" and "USER". To use the "default" cluster for all apps you need a string literal expression (with single quotes, and escaped with double quotes if it is in YAML as well): turbine: appConfig: customers,stores clusterNameExpression: "'default'" Spring Cloud provides a
Turbine StreamIn some environments (e.g. in a PaaS setting), the classic Turbine model of pulling metrics from all the distributed Hystrix commands doesn’t work. In that case you might want to have your Hystrix commands push metrics to Turbine, and Spring Cloud enables that with messaging. All you need to do on the client is add a dependency to On the server side Just create a Spring Boot application and annotate it with You can then point the Hystrix Dashboard to the Turbine Stream Server instead of individual Hystrix streams. If Turbine Stream is running on port 8989 on myhost, then put Spring Cloud provides a Client Side Load Balancer: RibbonRibbon is a client side load balancer which gives you a lot of control
over the behaviour of HTTP and TCP clients. Feign already uses Ribbon,
so if you are using A central concept in Ribbon is that of the named client. Each load
balancer is part of an ensemble of components that work together to
contact a remote server on demand, and the ensemble has a name that
you give it as an application developer (e.g. using the Customizing the Ribbon ClientYou can configure some bits of a Ribbon client using external
properties in Spring Cloud also lets you take full control of the client by
declaring additional configuration (on top of the
In this case the client is composed from the components already in
Spring Cloud Netflix provides the following beans by default for ribbon
(
Creating a bean of one of those type and placing it in a
This replaces the Using Ribbon with EurekaWhen Eureka is used in conjunction with Ribbon the
Example: How to Use Ribbon Without EurekaEureka is a convenient way to abstract the discovery of remote servers
so you don’t have to hard code their URLs in clients, but if you
prefer not to use it, Ribbon and Feign are still quite
amenable. Suppose you have declared a application.yml
stores:
ribbon:
listOfServers: example.com,google.com
Example: Disable Eureka use in RibbonSetting the property application.yml
ribbon: eureka: enabled: false Using the Ribbon API DirectlyYou can also use the
Declarative REST Client: FeignFeign 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 Example spring boot app
StoreClient.java
In the The Ribbon client above will want to discover the physical addresses for the "stores" service. If your application is a Eureka client then it will resolve the service in the Eureka service registry. If you don’t want to use Eureka, you can simply configure a list of servers in your external configuration (see above for example). Overriding Feign DefaultsA central concept in Spring Cloud’s Feign support is that of the named client. Each feign client is part of an ensemble of components that work together to contact a remote server on demand, and the ensemble has a name that you give it as an application developer using the Spring Cloud lets you take full control of the feign client by declaring additional configuration (on top of the
In this case the client is composed from the components already in
Placeholders are supported in the
Spring Cloud Netflix provides the following beans by default for feign (
Spring Cloud Netflix does not provide the following beans by default for feign, but still looks up beans of these types from the application context to create the feign client:
Creating a bean of one of those type and placing it in a
This replaces the Default configurations can be specified in the Feign Hystrix SupportIf Hystrix is on the classpath, by default Feign will wrap all methods with a circuit breaker. Returning a To disable Hystrix support for Feign, set To disable Hystrix support on a per-client basis create a vanilla
Feign Hystrix FallbacksHystrix supports the notion of a fallback: a default code path that is executed when they circuit is open or there is an error. To enable fallbacks for a given
Feign Inheritance SupportFeign supports boilerplate apis via single-inheritance interfaces. This allows grouping common operations into convenient base interfaces. UserService.java
UserResource.java
UserClient.java
Feign request/response compressionYou may consider enabling the request or response GZIP compression for your Feign requests. You can do this by enabling one of the properties:
Feign request compression gives you settings similar to what you may set for your web server:
These properties allow you to be selective about the compressed media types and minimum request threshold length. Feign loggingA logger is created for each Feign client created. By default the name of the logger is the full class name of the interface used to create the Feign client. Feign logging only responds to the application.yml
The
For example, the following would set the
External Configuration: ArchaiusArchaius 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 Example
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: ZuulRouting in an integral part of a microservice architecture. For example, Netflix uses Zuul for the following:
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 ProxySpring 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. This feature is useful for a user interface to proxy to the backend services it requires, avoiding the need to manage CORS and authentication concerns independently for all the backends. To enable it, annotate a Spring Boot main class with
To skip having a service automatically added, set
application.yml
In this example, all services are ignored except "users". To augment or change the proxy routes, you can add external configuration like the following: application.yml
This means that http calls to "/myusers" get forwarded to the "users" service (for example "/myusers/101" is forwarded to "/101"). To get more fine-grained control over a route you can specify the path and the serviceId independently: application.yml
This means that http calls to "/myusers" get forwarded to the "users_service" service. The route has to have a "path" which can be specified as an ant-style pattern, so "/myusers/*" only matches one level, but "/myusers/**" matches hierarchically. The location of the backend can be specified as either a "serviceId" (for a service from discovery) or a "url" (for a physical location), e.g. application.yml
These simple url-routes don’t get executed as a application.yml
You can provide convention between serviceId and routes using regexmapper. It uses regular expression named groups to extract variables from serviceId and inject them into a route pattern. ApplicationConfiguration.java
This means that a serviceId "myusers-v1" will be mapped to route "/v1/myusers/**". Any regular expression is accepted but all named groups must be present in both servicePattern and routePattern. If servicePattern does not match a serviceId, the default behavior is used. In the example above, a serviceId "myusers" will be mapped to route "/myusers/**" (no version detected) This feature is disable by default and only applies to discovered services. To add a prefix to all mappings, set application.yml
In this example, requests to "/myusers/101" will be forwarded to "/myusers/101" on the "users" service. The The An application with If more fine-grained ignoring is needed, you can specify specific patterns to ignore. These patterns are evaluated at the start of the route location process, which means prefixes should be included in the pattern to warrant a match. Ignored patterns span all services and supersede any other route specification. application.yml
This means that all calls such as "/myusers/101" will be forwarded to "/101" on the "users" service. But calls including "/admin/" will not resolve. Cookies and Sensitive HeadersIt’s OK to share headers between services in the same system, but you probably don’t want sensitive headers leaking downstream into external servers. You can specify a list of ignored headers as part of the route configuration. Cookies play a special role because they have well-defined semantics in browsers, and they are always to be treated as sensitive. If the consumer of your proxy is a browser, then cookies for downstream services also cause problems for the user because they all get jumbled up (all downstream services look like they come from the same place). If you are careful with the design of your services, for example if only one of the downstream services sets cookies, then you might be able to let them flow from the backend all the way up to the caller. Also, if your proxy sets cookies and all your back end services are part of the same system, it can be natural to simply share them (and for instance use Spring Session to link them up to some shared state). Other than that, any cookies that get set by downstream services are likely to be not very useful to the caller, so it is recommended that you make (at least) "Set-Cookie" and "Cookie" into sensitive headers for routes that are not part of your domain. Even for routes that are part of your domain, try to think carefully about what it means before allowing cookies to flow between them and the proxy. The sensitive headers can be configured as a comma-separated list per route, e.g. application.yml
Sensitive headers can also be set globally by setting
In addition to the per-route sensitive headers, you can set a global
value for The Routes EndpointIf you are using
Strangulation Patterns and Local ForwardsA common pattern when migrating an existing application or API is to "strangle" old endpoints, slowly replacing them with different implementations. The Zuul proxy is a useful tool for this because you can use it to handle all traffic from clients of the old endpoints, but redirect some of the requests to new ones. Example configuration: application.yml
In this example we are strangling the "legacy" app which is mapped to
all requests that do not match one of the other patterns. Paths in
Uploading Files through ZuulIf you application.yml
Note that for streaming to work with large files, you need to use chunked encoding in the request (which some browsers do not do by default). E.g. on the command line: $ curl -v -H "Transfer-Encoding: chunked" \
-F "[email protected]" localhost:9999/zuul/simple/file
Plain Embedded ZuulYou can also run a Zuul server without the proxying, or switch on parts of the proxying platform selectively, if you
use In this case the routes into the Zuul server are still specified by configuring "zuul.routes.*", but there is no service discovery and no proxying, so the "serviceId" and "url" settings are ignored. For example: application.yml
maps all paths in "/api/**" to the Zuul filter chain. Disable Zuul FiltersZuul for Spring Cloud comes with a number of Polyglot support with SidecarDo you have non-jvm languages you want to take advantage of Eureka, Ribbon and Config Server? The Spring Cloud Netflix Sidecar was inspired by Netflix Prana. It includes a simple http api to get all of the instances (ie host and port) for a given service. You can also proxy service calls through an embedded Zuul proxy which gets its route entries from Eureka. The Spring Cloud Config Server can be accessed directly via host lookup or through the Zuul Proxy. The non-jvm app should implement a health check so the Sidecar can report to eureka if the app is up or down. To enable the Sidecar, create a Spring Boot application with To configure the side car add health-uri-document
Here is an example application.yml for a Sidecar application: application.yml
The api for the /hosts/customers
The Zuul proxy automatically adds routes for each service known in eureka to
If the Config Server is registered with Eureka, non-jvm application can access
it via the Zuul proxy. If the serviceId of the ConfigServer is Non-jvm app can take advantage of the Config Server’s ability to return YAML documents. For example, a call to http://sidecar.local.spring.io:5678/configserver/default-master.yml might result in a YAML document like the following
RxJava with Spring MVCSpring Cloud Netflix includes the RxJava.
Spring Cloud Netflix provides support for returning Here are some examples of using
If you have an
If you have a streaming endpoint and client, SSE could be an option. To convert
Metrics: Spectator, Servo, and AtlasWhen used together, Spectator/Servo and Atlas provide a near real-time operational insight platform. Spectator and Servo are Netflix’s metrics collection libraries. Atlas is a Netflix metrics backend to manage dimensional time series data. Servo served Netflix for several years and is still usable, but is gradually being phased out in favor of Spectator, which is only designed to work with Java 8. Spring Cloud Netflix provides support for both, but Java 8 based applications are encouraged to use Spectator. Dimensional vs. Hierarchical MetricsSpring Boot Actuator metrics are hierarchical and metrics are separated only by name. These names often follow a naming convention that embeds key/value attribute pairs (dimensions) into the name separated by periods. Consider the following metrics for two endpoints, root and star-star:
The first metric gives us a normalized count of successful requests against the root endpoint per unit of time. But what if the system had 20 endpoints and you want to get a count of successful requests against all the endpoints? Some hierarchical metrics backends would allow you to specify a wild card such as Even in the presence of wildcarding support on a hierarchical metrics backend, naming consistency can be difficult. Specifically the position of these tags in the name string can slip with time, breaking queries. For example, suppose we add an additional dimension to the hierarchical metrics above for HTTP method. Then Netflix metrics are tagged (a.k.a. dimensional). Each metric has a name, but this single named metric can contain multiple statistics and 'tag' key/value pairs that allows more querying flexibility. In fact, the statistics themselves are recorded in a special tag. Recorded with Netflix Servo or Spectator, a timer for the root endpoint described above contains 4 statistics per status code, where the count statistic is identical to Spring Boot Actuator’s counter. In the event that we have encountered an HTTP 200 and 400 thus far, there will be 8 available data points:
Default Metrics CollectionWithout any additional dependencies or configuration, a Spring Cloud based service will autoconfigure a Servo
Set the If Spring AOP is enabled and
Metrics Collection: SpectatorTo enable Spectator metrics, include a dependency on
In Spectator parlance, a meter is a named, typed, and tagged configuration and a metric represents the value of a given meter at a point in time. Spectator meters are created and controlled by a registry, which currently has several different implementations. Spectator provides 4 meter types: counter, timer, gauge, and distribution summary. Spring Cloud Spectator integration configures an injectable Spectator CounterA counter is used to measure the rate at which some event is occurring.
The counter records a single time-normalized statistic. Spectator TimerA timer is used to measure how long some event is taking. Spring Cloud automatically records timers for Spring MVC requests and conditionally Request Latency
image::RequestLatency.png []
The timer simultaneously records 4 statistics: count, max, totalOfSquares, and totalTime. The count statistic will always match the single normalized value provided by a counter if you had called For long running operations, Spectator provides a special Spectator GaugeGauges are used to determine some current value like the size of a queue or number of threads in a running state. Since gauges are sampled, they provide no information about how these values fluctuate between samples. The normal use of a gauge involves registering the gauge once in initialization with an id, a reference to the object to be sampled, and a function to get or compute a numeric value based on the object. The reference to the object is passed in separately and the Spectator registry will keep a weak reference to the object. If the object is garbage collected, then Spectator will automatically drop the registration. See the note in Spectator’s documentation about potential memory leaks if this API is misused.
Spectator Distribution SummariesA distribution summary is used to track the distribution of events. It is similar to a timer, but more general in that the size does not have to be a period of time. For example, a distribution summary could be used to measure the payload sizes of requests hitting a server.
Metrics Collection: Servo
In Servo parlance, a monitor is a named, typed, and tagged configuration and a metric represents the value of a given monitor at a point in time. Servo monitors are logically equivalent to Spectator meters. Servo monitors are created and controlled by a Spring Cloud integration configures an injectable Creating Servo MonitorsIf you are using the Servo To manually create a Monitor type in Servo, especially for the more exotic monitor types for which convenience methods are not provided, instantiate the appropriate type by providing a
Metrics Backend: AtlasAtlas was developed by Netflix to manage dimensional time series data for near real-time operational insight. Atlas features in-memory data storage, allowing it to gather and report very large numbers of metrics, very quickly. Atlas captures operational intelligence. Whereas business intelligence is data gathered for analyzing trends over time, operational intelligence provides a picture of what is currently happening within a system. Spring Cloud provides a Global tagsSpring Cloud enables you to add tags to every metric sent to the Atlas backend. Global tags can be used to separate metrics by application name, environment, region, etc. Each bean implementing
Using AtlasTo bootstrap a in-memory standalone Atlas instance:
Once running and you have collected a handful of metrics, verify that your setup is correct by listing tags on the Atlas server:
The Atlas wiki contains a compilation of sample queries for various scenarios. Make sure to check out the alerting philosophy and docs on using double exponential smoothing to generate dynamic alert thresholds. Spring Cloud StreamThis section goes into more detail about how you can work with Spring Cloud Stream. It covers topics such as creating and running stream applications. Introducing Spring Cloud StreamSpring Cloud Stream is a framework for building message-driven microservice applications. Spring Cloud Stream builds upon Spring Boot to create standalone, production-grade Spring applications, and uses Spring Integration to provide connectivity to message brokers. It provides opinionated configuration of middleware from several vendors, introducing the concepts of persistent publish-subscribe semantics, consumer groups, and partitions. You can add the
The The following is the definition of the
The Spring Cloud Stream will create an implementation of the interface for you. You can use this in the application by autowiring it, as in the following example of a test case.
Main ConceptsSpring Cloud Stream provides a number of abstractions and primitives that simplify the writing of message-driven microservice applications. This section gives an overview of the following:
Application ModelA Spring Cloud Stream application consists of a middleware-neutral core. The application communicates with the outside world through input and output channels injected into it by Spring Cloud Stream. Channels are connected to external brokers through middleware-specific Binder implementations.
Figure 4. Spring Cloud Stream Application
Fat JARSpring Cloud Stream applications can be run in standalone mode from your IDE for testing. To run a Spring Cloud Stream application in production, you can create an executable (or "fat") JAR by using the standard Spring Boot tooling provided for Maven or Gradle. The Binder AbstractionSpring Cloud Stream provides Binder implementations for Kafka, Rabbit MQ, Redis, and Gemfire. Spring Cloud Stream also includes a TestSupportBinder, which leaves a channel unmodified so that tests can interact with channels directly and reliably assert on what is received. You can use the extensible API to write your own Binder. Spring Cloud Stream uses Spring Boot for configuration, and the Binder abstraction makes it possible for a Spring Cloud Stream application to be flexible in how it connects to middleware.
For example, deployers can dynamically choose, at runtime, the destinations (e.g., the Kafka topics or RabbitMQ exchanges) to which channels connect.
Such configuration can be provided through external configuration properties and in any form supported by Spring Boot (including application arguments, environment variables, and Spring Cloud Stream automatically detects and uses a binder found on the classpath. You can easily use different types of middleware with the same code: just include a different binder at build time. For more complex use cases, you can also package multiple binders with your application and have it choose the binder, and even whether to use different binders for different channels, at runtime. Persistent Publish-Subscribe SupportCommunication between applications follows a publish-subscribe model, where data is broadcast through shared topics. This can be seen in the following figure, which shows a typical deployment for a set of interacting Spring Cloud Stream applications.
Figure 5. Spring Cloud Stream Publish-Subscribe
Data reported by sensors to an HTTP endpoint is sent to a common destination named The publish-subscribe communication model reduces the complexity of both the producer and the consumer, and allows new applications to be added to the topology without disruption of the existing flow. For example, downstream from the average-calculating application, you can add an application that calculates the highest temperature values for display and monitoring. You can then add another application that interprets the same flow of averages for fault detection. Doing all communication through shared topics rather than point-to-point queues reduces coupling between microservices. While the concept of publish-subscribe messaging is not new, Spring Cloud Stream takes the extra step of making it an opinionated choice for its application model. By using native middleware support, Spring Cloud Stream also simplifies use of the publish-subscribe model across different platforms. Consumer GroupsWhile the publish-subscribe model makes it easy to connect applications through shared topics, the ability to scale up by creating multiple instances of a given application is equally important. When doing this, different instances of an application are placed in a competing consumer relationship, where only one of the instances is expected to handle a given message. Spring Cloud Stream models this behavior through the concept of a consumer group.
(Spring Cloud Stream consumer groups are similar to and inspired by Kafka consumer groups.)
Each consumer binding can use the
Figure 6. Spring Cloud Stream Consumer Groups
All groups which subscribe to a given destination receive a copy of published data, but only one member of each group receives a given message from that destination. By default, when a group is not specified, Spring Cloud Stream assigns the application to an anonymous and independent single-member consumer group that is in a publish-subscribe relationship with all other consumer groups. DurabilityConsistent with the opinionated application model of Spring Cloud Stream, consumer group subscriptions are durable. That is, a binder implementation ensures that group subscriptions are persistent, and once at least one subscription for a group has been created, the group will receive messages, even if they are sent while all applications in the group are stopped.
In general, it is preferable to always specify a consumer group when binding an application to a given destination. When scaling up a Spring Cloud Stream application, you must specify a consumer group for each of its input bindings. This prevents the application’s instances from receiving duplicate messages (unless that behavior is desired, which is unusual). Partitioning SupportSpring Cloud Stream provides support for partitioning data between multiple instances of a given application. In a partitioned scenario, the physical communication medium (e.g., the broker topic) is viewed as being structured into multiple partitions. One or more producer application instances send data to multiple consumer application instances and ensure that data identified by common characteristics are processed by the same consumer instance. Spring Cloud Stream provides a common abstraction for implementing partitioned processing use cases in a uniform fashion. Partitioning can thus be used whether the broker itself is naturally partitioned (e.g., Kafka) or not (e.g., RabbitMQ).
Figure 7. Spring Cloud Stream Partitioning
Partitioning is a critical concept in stateful processing, where it is critiical, for either performance or consistency reasons, to ensure that all related data is processed together. For example, in the time-windowed average calculation example, it is important that all measurements from any given sensor are processed by the same application instance.
Programming ModelThis section describes Spring Cloud Stream’s programming model. Spring Cloud Stream provides a number of predefined annotations for declaring bound input and output channels as well as how to listen to channels. Declaring and Binding ChannelsTriggering Binding Via
|
|
Note
|
In Spring Cloud Stream 1.0, the only supported bindable components are the Spring Messaging |
@Input and @OutputA Spring Cloud Stream application can have an arbitrary number of input and output channels defined in an interface as @Input and @Output methods:
public interface Barista {
@Input
SubscribableChannel orders();
@Output
MessageChannel hotDrinks();
@Output
MessageChannel coldDrinks();
}
Using this interface as a parameter to @EnableBinding will trigger the creation of three bound channels named orders, hotDrinks, and coldDrinks, respectively.
@EnableBinding(Barista.class)
public class CafeConfiguration {
...
}
Using the @Input and @Output annotations, you can specify a customized channel name for the channel, as shown in the following example:
public interface Barista {
...
@Input("inboundOrders")
SubscribableChannel orders();
}
In this example, the created bound channel will be named inboundOrders.
Source, Sink, and ProcessorFor easy addressing of the most common use cases, which involve either an input channel, an output channel, or both, Spring Cloud Stream provides three predefined interfaces out of the box.
Source can be used for an application which has a single outbound channel.
public interface Source {
String OUTPUT = "output";
@Output(Source.OUTPUT)
MessageChannel output();
}
Sink can be used for an application which has a single inbound channel.
public interface Sink {
String INPUT = "input";
@Input(Sink.INPUT)
SubscribableChannel input();
}
Processor can be used for an application which has both an inbound channel and an outbound channel.
public interface Processor extends Source, Sink {
}
Spring Cloud Stream provides no special handling for any of these interfaces; they are only provided out of the box.
For each bound interface, Spring Cloud Stream will generate a bean that implements the interface.
Invoking a @Input-annotated or @Output-annotated method of one of these beans will return the relevant bound channel.
The bean in the following example sends a message on the output channel when its hello method is invoked.
It invokes output() on the injected Source bean to retrieve the target channel.
@Component
public class SendingBean {
private Source source;
@Autowired
public SendingBean(Source source) {
this.source = source;
}
public void sayHello(String name) {
source.output().send(MessageBuilder.withPayload(body).build());
}
}
Bound channels can be also injected directly:
@Component
public class SendingBean {
private MessageChannel output;
@Autowired
public SendingBean(MessageChannel output) {
this.output = output;
}
public void sayHello(String name) {
output.send(MessageBuilder.withPayload(body).build());
}
}
If the name of the channel is customized on the declaring annotation, that name should be used instead of the method name. Given the following declaration:
public interface CustomSource {
...
@Output("customOutput")
MessageChannel output();
}
The channel will be injected as shown in the following example:
@Component
public class SendingBean {
@Autowired
private MessageChannel output;
@Autowired @Qualifier("customOutput")
public SendingBean(MessageChannel output) {
this.output = output;
}
public void sayHello(String name) {
customOutput.send(MessageBuilder.withPayload(body).build());
}
}
You can write a Spring Cloud Stream application using either Spring Integration annotations or Spring Cloud Stream’s @StreamListener annotation.
The @StreamListener annotation is modeled after other Spring Messaging annotations (such as @MessageMapping, @JmsListener, @RabbitListener, etc.) but adds content type management and type coercion features.
Because Spring Cloud Stream is based on Spring Integration, Stream completely inherits Integration’s foundation and infrastructure as well as the component itself.
For example, you can attach the output channel of a Source to a MessageSource:
@EnableBinding(Source.class)
public class TimerSource {
@Value("${format}")
private String format;
@Bean
@InboundChannelAdapter(value = Source.OUTPUT, poller = @Poller(fixedDelay = "${fixedDelay}", maxMessagesPerPoll = "1"))
public MessageSource<String> timerMessageSource() {
return () -> new GenericMessage<>(new SimpleDateFormat(format).format(new Date()));
}
}
Or you can use a processor’s channels in a transformer:
@EnableBinding(Processor.class)
public class TransformProcessor {
@Transformer(inputChannel = Processor.INPUT, outputChannel = Processor.OUTPUT)
public Object transform(String message) {
return message.toUpper();
}
}
Complementary to its Spring Integration support, Spring Cloud Stream provides its own @StreamListener annotation, modeled after other Spring Messaging annotations (e.g. @MessageMapping, @JmsListener, @RabbitListener, etc.).
The @StreamListener annotation provides a simpler model for handling inbound messages, especially when dealing with use cases that involve content type management and type coercion.
Spring Cloud Stream provides an extensible MessageConverter mechanism for handling data conversion by bound channels and for, in this case, dispatching to methods annotated with @StreamListener.
The following is an example of an application which processes external Vote events:
@EnableBinding(Sink.class)
public class VoteHandler {
@Autowired
VotingService votingService;
@StreamListener(Sink.INPUT)
public void handle(Vote vote) {
votingService.record(vote);
}
}
The distinction between @StreamListener and a Spring Integration @ServiceActivator is seen when considering an inbound Message that has a String payload and a contentType header of application/json.
In the case of @StreamListener, the MessageConverter mechanism will use the contentType header to parse the String payload into a Vote object.
As with other Spring Messaging methods, method arguments can be annotated with @Payload, @Headers and @Header.
|
Note
|
For methods which return data, you must use the
|
|
Note
|
In the case of RabbitMQ, content type headers can be set by external applications. Spring Cloud Stream supports them as part of an extended internal protocol used for any type of transport (including transports, such as Kafka, that do not normally support headers). |
Spring Cloud Stream provides support for aggregating multiple applications together, connecting their input and output channels directly and avoiding the additional cost of exchanging messages via a broker. As of version 1.0 of Spring Cloud Stream, aggregation is supported only for the following types of applications:
sources - applications with a single output channel named output, typically having a single binding of the type org.springframework.cloud.stream.messaging.Source
sinks - applications with a single input channel named input, typically having a single binding of the type org.springframework.cloud.stream.messaging.Sink
processors - applications with a single input channel named input and a single output channel named output, typically having a single binding of the type org.springframework.cloud.stream.messaging.Processor.
They can be aggregated together by creating a sequence of interconnected applications, in which the output channel of an element in the sequence is connected to the input channel of the next element, if it exists. A sequence can start with either a source or a processor, it can contain an arbitrary number of processors and must end with either a processor or a sink.
Depending on the nature of the starting and ending element, the sequence may have one or more bindable channels, as follows:
if the sequence starts with a source and ends with a sink, all communication between the applications is direct and no channels will be bound
if the sequence starts with a processor, then its input channel will become the input channel of the aggregate and will be bound accordingly
if the sequence ends with a processor, then its output channel will become the output channel of the aggregate and will be bound accordingly
Aggregation is performed using the AggregateApplicationBuilder utility class, as in the following example.
Let’s consider a project in which we have source, processor and a sink, which may be defined in the project, or may be contained in one of the project’s dependencies.
@SpringBootApplication
@EnableBinding(Sink.class)
public class SinkApplication {
private static Logger logger = LoggerFactory.getLogger(SinkModuleDefinition.class);
@ServiceActivator(inputChannel=Sink.INPUT)
public void loggerSink(Object payload) {
logger.info("Received: " + payload);
}
}
@SpringBootApplication
@EnableBinding(Processor.class)
public class ProcessorApplication {
@Transformer
public String loggerSink(String payload) {
return payload.toUpperCase();
}
}
@SpringBootApplication
@EnableBinding(Source.class)
public class SourceApplication {
@Bean
@InboundChannelAdapter(value = Source.OUTPUT)
public String timerMessageSource() {
return new SimpleDateFormat().format(new Date());
}
}
Each configuration can be used for running a separate component, but in this case they can be aggregated together as follows:
@SpringBootApplication
public class SampleAggregateApplication {
public static void main(String[] args) {
new AggregateApplicationBuilder()
.from(SourceApplication.class).args("--fixedDelay=5000")
.via(ProcessorApplication.class)
.to(SinkApplication.class).args("--debug=true").run(args);
}
}
The starting component of the sequence is provided as argument to the from() method.
The ending component of the sequence is provided as argument to the to() method.
Intermediate processors are provided as argument to the via() method.
Multiple processors of the same type can be chained together (e.g. for pipelining transformations with different configurations).
For each component, the builder can provide runtime arguments for Spring Boot configuration.
Spring Cloud Stream provides support for RxJava-based processors through the RxJavaProcessor available in spring-cloud-stream-rxjava.
public interface RxJavaProcessor<I, O> {
Observable<O> process(Observable<I> input);
}
An implementation of RxJavaProcessor will receive Observable as an input that represents the flow of inbound message payloads.
The process method is invoked once at startup for setting up the data flow.
You can enable the use of RxJava-based processors and use them in your processor application by using the @EnableRxJavaProcessor annotation.
@EnableRxJavaProcessor is meta-annotated with @EnableBinding(Processor.class) and will create the Processor binding.
Here is an example of an RxJava-based processor:
@EnableRxJavaProcessor
public class RxJavaTransformer {
private static Logger logger = LoggerFactory.getLogger(RxJavaTransformer.class);
@Bean
public RxJavaProcessor<String,String> processor() {
return inputStream -> inputStream.map(data -> {
logger.info("Got data = " + data);
return data;
})
.buffer(5)
.map(data -> String.valueOf(avg(data)));
}
private static Double avg(List<String> data) {
double sum = 0;
double count = 0;
for(String d : data) {
count++;
sum += Double.valueOf(d);
}
return sum/count;
}
}
|
Note
|
When implementing an RxJava processor, it is important to handle exceptions as part of your processing flow.
Uncaught exceptions will be treated as errors by RxJava and will cause the |
Spring Cloud Stream provides a Binder abstraction for use in connecting to physical destinations at the external middleware. This section provides information about the main concepts behind the Binder SPI, its main components, and implementation-specific details.
A producer is any component that sends messages to a channel.
The channel can be bound to an external message broker via a Binder implementation for that broker.
When invoking the bindProducer() method, the first parameter is the name of the destination within the broker, the second parameter is the local channel instance to which the producer will send messages, and the third parameter contains properties (such as a partition key expression) to be used within the adapter that is created for that channel.
A consumer is any component that receives messages from a channel.
As with a producer, the consumer’s channel can be bound to an external message broker.
When invoking the bindConsumer() method, the first parameter is the destination name, and a second parameter provides the name of a logical group of consumers.
Each group that is represented by consumer bindings for a given destination receives a copy of each message that a producer sends to that destination (i.e., publish-subscribe semantics).
If there are multiple consumer instances bound using the same group name, then messages will be load-balanced across those consumer instances so that each message sent by a producer is consumed by only a single consumer instance within each group (i.e., queueing semantics).
The Binder SPI consists of a number of interfaces, out-of-the box utility classes and discovery strategies that provide a pluggable mechanism for connecting to external middleware.
The key point of the SPI is the Binder interface which is a strategy for connecting inputs and outputs to external middleware.
public interface Binder<T, C extends ConsumerProperties, P extends ProducerProperties> {
Binding<T> bindConsumer(String name, String group, T inboundBindTarget, C consumerProperties);
Binding<T> bindProducer(String name, T outboundBindTarget, P producerProperties);
}
The interface is parameterized, offering a number of extension points:
input and output bind targets - as of version 1.0, only MessageChannel is supported, but this is intended to be used as an extension point in the future;
extended consumer and producer properties - allowing specific Binder implementations to add supplemental properties which can be supported in a type-safe manner.
A typical binder implementation consists of the following
a class that implements the Binder interface;
a Spring @Configuration class that creates a bean of the type above along with the middleware connection infrastructure;
a META-INF/spring.binders file found on the classpath containing one or more binder definitions, e.g.
kafka:\
org.springframework.cloud.stream.binder.kafka.config.KafkaBinderConfiguration
Spring Cloud Stream relies on implementations of the Binder SPI to perform the task of connecting channels to message brokers. Each Binder implementation typically connects to one type of messaging system. Out of the box, Spring Cloud Stream provides binders for Kafka, RabbitMQ, and Redis.
By default, Spring Cloud Stream relies on Spring Boot’s auto-configuration to configure the binding process. If a single Binder implementation is found on the classpath, Spring Cloud Stream will use it automatically. For example, a Spring Cloud Stream project that aims to bind only to RabbitMQ can simply add the following dependency:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-stream-binder-rabbit</artifactId>
</dependency>
When multiple binders are present on the classpath, the application must indicate which binder is to be used for each channel binding.
Each binder configuration contains a META-INF/spring.binders, which is a simple properties file:
rabbit:\
org.springframework.cloud.stream.binder.rabbit.config.RabbitServiceAutoConfiguration
Similar files exist for the other provided binder implementations (e.g., Kafka), and custom binder implementations are expected to provide them, as well.
The key represents an identifying name for the binder implementation, whereas the value is a comma-separated list of configuration classes that each contain one and only one bean definition of type org.springframework.cloud.stream.binder.Binder.
Binder selection can either be performed globally, using the spring.cloud.stream.defaultBinder property (e.g., spring.cloud.stream.defaultBinder=rabbit) or individually, by configuring the binder on each channel binding.
For instance, a processor application which reads from Kafka and writes to RabbitMQ can specify the following configuration:
spring.cloud.stream.bindings.input.binder=kafka spring.cloud.stream.bindings.output.binder=rabbit
By default, binders share the application’s Spring Boot auto-configuration, so that one instance of each binder found on the classpath will be created. If your application should connect to more than one broker of the same type, you can specify multiple binder configurations, each with different environment settings.
|
Note
|
Turning on explicit binder configuration will disable the default binder configuration process altogether.
If you do this, all binders in use must be included in the configuration.
Frameworks that intend to use Spring Cloud Stream transparently may create binder configurations that can be referenced by name, but will not affect the default binder configuration.
In order to do so, a binder configuration may have its |
For example, this is the typical configuration for a processor application which connects to two RabbitMQ broker instances:
spring:
cloud:
stream:
bindings:
input:
destination: foo
binder: rabbit1
output:
destination: bar
binder: rabbit2
binders:
rabbit1:
type: rabbit
environment:
spring:
rabbitmq:
host: <host1>
rabbit2:
type: rabbit
environment:
spring:
rabbitmq:
host: <host2>
The following properties are available when creating custom binder configurations.
They must be prefixed with spring.cloud.stream.binders.<configurationName>.
The binder type.
It typically references one of the binders found on the classpath, in particular a key in a META-INF/spring.binders file.
By default, it has the same value as the configuration name.
Whether the configuration will inherit the environment of the application itself.
Default true.
Root for a set of properties that can be used to customize the environment of the binder. When this is configured, the context in which the binder is being created is not a child of the application context. This allows for complete separation between the binder components and the application components.
Default empty.
Whether the binder configuration is a candidate for being considered a default binder, or can be used only when explicitly referenced. This allows adding binder configurations without interfering with the default processing.
Default true.
This section details the binder implementation strategies for Kafka and Rabbit MQ, in what concerns mapping the Spring Cloud Stream concepts onto the middleware concepts.
The Kafka Binder implementation maps the destination to a Kafka topic. The consumer group maps directly to the same Kafka concept. Spring Cloud Stream does not use the high-level consumer, but implements a similar concept for the simple consumer.
The RabbitMQ Binder implementation maps the destination to a TopicExchange.
For each consumer group, a Queue will be bound to that TopicExchange.
Each consumer instance that binds will trigger creation of a corresponding RabbitMQ Consumer instance for its group’s Queue.
Spring Cloud Stream supports general configuration options as well as configuration for bindings and binders. Some binders allow additional binding properties to support middleware-specific features.
Configuration options can be provided to Spring Cloud Stream applications via any mechanism supported by Spring Boot. This includes application arguments, environment variables, and YAML or .properties files.
The number of deployed instances of an application. Must be set for partitioning and if using Kafka.
Default: 1.
The instance index of the application: a number from 0 to instanceCount-1.
Used for partitioning and with Kafka.
Automatically set in Cloud Foundry to match the application’s instance index.
A list of destinations that can be bound dynamically (for example, in a dynamic routing scenario). If set, only listed destinations can be bound.
Default: empty (allowing any destination to be bound).
The default binder to use, if multiple binders are configured. See Multiple Binders on the Classpath.
Default: empty.
This property is only applicable when the cloud profile is active and Spring Cloud Connectors are provided with the application.
If the property is false (the default), the binder will detect a suitable bound service (e.g. a RabbitMQ service bound in Cloud Foundry for the RabbitMQ binder) and will use it for creating connections (usually via Spring Cloud Connectors).
When set to true, this property instructs binders to completely ignore the bound services and rely on Spring Boot properties (e.g. relying on the spring.rabbitmq.* properties provided in the environment for the RabbitMQ binder).
The typical usage of this property is to be nested in a customized environment when connecting to multiple systems.
Default: false.
Binding properties are supplied using the format spring.cloud.stream.bindings.<channelName>.<property>=<value>.
The <channelName> represents the name of the channel being configured (e.g., output for a Source).
In what follows, we indicate where we have omitted the spring.cloud.stream.bindings.<channelName>. prefix and focus just on the property name, with the understanding that the prefix will be included at runtime.
The following binding properties are available for both input and output bindings and
must be prefixed with spring.cloud.stream.bindings.<channelName>..
The target destination of a channel on the bound middleware (e.g., the RabbitMQ exchange or Kafka topic). If the channel is bound as a consumer, it could be bound to multiple destinations and the destination names can be specified as comma separated String values. If not set, the channel name is used instead.
The consumer group of the channel. Applies only to inbound bindings. See Consumer Groups.
Default: null (indicating an anonymous consumer).
The content type of the channel. //See [content type management].
Default: null (so that no type coercion is performed).
The binder used by this binding. See Multiple Binders on the Classpath for details.
Default: null (the default binder will be used, if one exists).
The following binding properties are available for input bindings only and must be prefixed with spring.cloud.stream.bindings.<channelName>.consumer..
The concurrency of the inbound consumer.
Default: 1.
Whether the consumer receives data from a partitioned producer.
Default: false.
When set to raw, disables header parsing on input.
Effective only for messaging middleware that does not support message headers natively and requires header embedding.
Useful when inbound data is coming from outside Spring Cloud Stream applications.
Default: embeddedHeaders.
The number of attempts of re-processing an inbound message.
Default: 3.
The backoff initial interval on retry.
Default: 1000.
The maximum backoff interval.
Default: 10000.
The backoff multiplier.
Default: 2.0.
The following binding properties are available for output bindings only and must be prefixed with spring.cloud.stream.bindings.<channelName>.producer..
A SpEL expression that determines how to partition outbound data.
If set, or if partitionKeyExtractorClass is set, outbound data on this channel will be partitioned, and partitionCount must be set to a value greater than 1 to be effective.
The two options are mutually exclusive.
See Partitioning Support.
Default: null.
A PartitionKeyExtractorStrategy implementation.
If set, or if partitionKeyExpression is set, outbound data on this channel will be partitioned, and partitionCount must be set to a value greater than 1 to be effective.
The two options are mutually exclusive.
See Partitioning Support.
Default: null.
A PartitionSelectorStrategy implementation.
Mutually exclusive with partitionSelectorExpression.
If neither is set, the partition will be selected as the hashCode(key) % partitionCount, where key is computed via either partitionKeyExpression or partitionKeyExtractorClass.
Default: null.
A SpEL expression for customizing partition selection.
Mutually exclusive with partitionSelectorClass.
If neither is set, the partition will be selected as the hashCode(key) % partitionCount, where key is computed via either partitionKeyExpression or partitionKeyExtractorClass.
Default: null.
The number of target partitions for the data, if partitioning is enabled. Must be set to a value greater than 1 if the producer is partitioned. On Kafka, interpreted as a hint; the larger of this and the partition count of the target topic is used instead.
Default: 1.
A comma-separated list of groups to which the producer must ensure message delivery even if they start after it has been created (e.g., by pre-creating durable queues in RabbitMQ).
When set to raw, disables header embedding on output.
Effective only for messaging middleware that does not support message headers natively and requires header embedding.
Useful when producing data for non-Spring Cloud Stream applications.
Default: embeddedHeaders.
The following binder, consumer, and producer properties are specific to binder implementations.
By default, the RabbitMQ binder uses Spring Boot’s ConnectionFactory, and it therefore supports all Spring Boot configuration options for RabbitMQ.
(For reference, consult the Spring Boot documentation.) RabbitMQ configuration options use the spring.rabbitmq prefix.
In addition to the Spring Boot options, the RabbitMQ binder supports the following properties:
A comma-separated list of RabbitMQ management plugin URLs.
Only used when nodes contains more than one entry.
Each entry in this list must have a corresponding entry in spring.rabbitmq.addresses.
Default: empty.
A comma-separated list of RabbitMQ node names.
When more than one entry, used to locate the server address where a queue is located.
Each entry in this list must have a corresponding entry in spring.rabbitmq.addresses.
Default: empty.
Compression level for compressed bindings.
See java.util.zip.Deflater.
Default: 1 (BEST_LEVEL).
The following properties are available for Rabbit consumers only and
must be prefixed with spring.cloud.stream.rabbit.bindings.<channelName>.consumer..
The acknowledge mode.
Default: AUTO.
Whether to automatically declare the DLQ and bind it to the binder DLX.
Default: false.
Whether subscription should be durable.
Only effective if group is also set.
Default: true.
Default: 1.
Prefetch count.
Default: 1.
A prefix to be added to the name of the destination and queues.
Default: "".
The interval between connection recovery attempts, in milliseconds.
Default: 5000.
Whether delivery failures should be requeued.
Default: true.
The request headers to be transported.
Default: [STANDARD_REQUEST_HEADERS,'*'].
The reply headers to be transported.
Default: [STANDARD_REPLY_HEADERS,'*'].
By default, messages which fail after retries are exhausted are rejected.
If a dead-letter queue (DLQ) is configured, RabbitMQ will route the failed message (unchanged) to the DLQ.
If set to true, the bus will republish failed messages to the DLQ with additional headers, including the exception message and stack trace from the cause of the final failure.
Whether to use transacted channels.
Default: false.
The number of deliveries between acks.
Default: 1.
The following properties are available for Rabbit producers only and
must be prefixed with spring.cloud.stream.rabbit.bindings.<channelName>.producer..
Whether to automatically declare the DLQ and bind it to the binder DLX.
Default: false.
Whether to enable message batching by producers.
Default: false.
The number of messages to buffer when batching is enabled.
Default: 100.
Default: 10000.
Default: 5000.
Whether data should be compressed when sent.
Default: false.
Delivery mode.
Default: PERSISTENT.
A prefix to be added to the name of the destination exchange.
Default: "".
The request headers to be transported.
Default: [STANDARD_REQUEST_HEADERS,'*'].
The reply headers to be transported.
Default: [STANDARD_REPLY_HEADERS,'*'].
A list of brokers to which the Kafka binder will connect.
Default: localhost.
brokers allows hosts specified with or without port information (e.g., host1,host2:port2).
This sets the default port when no port is configured in the broker list.
Default: 9092.
A list of ZooKeeper nodes to which the Kafka binder can connect.
Default: localhost.
zkNodes allows hosts specified with or without port information (e.g., host1,host2:port2).
This sets the default port when no port is configured in the node list.
Default: 2181.
The list of custom headers that will be transported by the binder.
Default: empty.
The frequency, in milliseconds, with which offsets are saved.
Ignored if 0.
Default: 10000.
The frequency, in number of updates, which which consumed offsets are persisted.
Ignored if 0.
Mutually exclusive with offsetUpdateTimeWindow.
Default: 0.
The number of required acks on the broker.
Default: 1.
Effective only if autoCreateTopics or autoAddPartitions is set.
The global minimum number of partitions that the binder will configure on topics on which it produces/consumes data.
It can be superseded by the partitionCount setting of the producer or by the value of instanceCount * concurrency settings of the producer (if either is larger).
Default: 1.
The replication factor of auto-created topics if autoCreateTopics is active.
Default: 1.
If set to true, the binder will create new topics automatically.
If set to false, the binder will rely on the topics being already configured.
In the latter case, if the topics do not exist, the binder will fail to start.
Of note, this setting is independent of the auto.topic.create.enable setting of the broker and it does not influence it: if the server is set to auto-create topics, they may be created as part of the metadata retrieval request, with default broker settings.
Default: true.
If set to true, the binder will create add new partitions if required.
If set to false, the binder will rely on the partition size of the topic being already configured.
If the partition count of the target topic is smaller than the expected value, the binder will fail to start.
Default: false.
Size (in bytes) of the socket buffer to be used by the Kafka consumers.
Default: 2097152.
The following properties are available for Kafka consumers only and
must be prefixed with spring.cloud.stream.kafka.bindings.<channelName>.consumer..
Whether to autocommit offsets when a message has been processed.
If set to false, an Acknowledgment header will be available in the message headers for late acknowledgment.
Default: true.
Effective only if autoCommitOffset is set to true.
If set to false it suppresses auto-commits for messages that result in errors, and will commit only for successful messages, allows a stream to automatically replay from the last successfully processed message, in case of persistent failures.
If set to true, it will always auto-commit (if auto-commit is enabled).
If not set (default), it effectively has the same value as enableDlq, auto-committing erroneous messages if they are sent to a DLQ, and not committing them otherwise.
Default: not set.
The interval between connection recovery attempts, in milliseconds.
Default: 5000.
Whether to reset offsets on the consumer to the value provided by startOffset.
Default: false.
The starting offset for new groups, or when resetOffsets is true.
Allowed values: earliest, latest.
Default: null (equivalent to earliest).
When set to true, it will send enable DLQ behavior for the consumer.
Messages that result in errors will be forwarded to a topic named error.<destination>.<group>.
This provides an alternative option to the more common Kafka replay scenario for the case when the number of errors is relatively small and replaying the entire original topic may be too cumbersome.
Default: false.
The following properties are available for Kafka producers only and
must be prefixed with spring.cloud.stream.kafka.bindings.<channelName>.producer..
Upper limit, in bytes, of how much data the Kafka producer will attempt to batch before sending.
Default: 16384.
Whether the producer is synchronous.
Default: false.
How long the producer will wait before sending in order to allow more messages to accumulate in the same batch. (Normally the producer does not wait at all, and simply sends all the messages that accumulated while the previous send was in progress.) A non-zero value may increase throughput at the expense of latency.
Default: 0.
The maximum size of a message sending request.
Default: 1048576.
Map with a key/value pair containing generic Kafka producer properties.
Default: Empty map.
To allow you to propagate information about the content type of produced messages, Spring Cloud Stream attaches, by default, a contentType header to outbound messages.
For middleware that does not directly support headers, Spring Cloud Stream provides its own mechanism of automatically wrapping outbound messages in an envelope of its own.
For middleware that does support headers, Spring Cloud Stream applications may receive messages with a given content type from non-Spring Cloud Stream applications.
Spring Cloud Stream can handle messages based on this information in two ways:
Through its contentType settings on inbound and outbound channels
Through its argument mapping performed for methods annotated with @StreamListener
Spring Cloud Stream allows you to declaratively configure type conversion for inputs and outputs using the content-type property of a binding.
Note that general type conversion may also be accomplished easily by using a transformer inside your application.
Currently, Spring Cloud Stream natively supports the following type conversions commonly used in streams:
JSON to/from POJO
JSON to/from org.springframework.tuple.Tuple
Object to/from byte[] : Either the raw bytes serialized for remote transport, bytes emitted by an application, or converted to bytes using Java serialization(requires the object to be Serializable)
String to/from byte[]
Object to plain text (invokes the object’s toString() method)
Where JSON represents either a byte array or String payload containing JSON. Currently, Objects may be converted from a JSON byte array or String. Converting to JSON always produces a String.
content-type values are parsed as media types, e.g., application/json or text/plain;charset=UTF-8.
MIME types are especially useful for indicating how to convert to String or byte[] content.
Spring Cloud Stream also uses MIME type format to represent Java types, using the general type application/x-java-object with a type parameter.
For example, application/x-java-object;type=java.util.Map or application/x-java-object;type=com.bar.Foo can be set as the content-type property of an input binding.
In addition, Spring Cloud Stream provides custom MIME types, notably, application/x-spring-tuple to specify a Tuple.
The type conversions Spring Cloud Stream provides out of the box are summarized in the following table:
| Source Payload | Target Payload | content-type header | content-type | Comments |
|---|---|---|---|---|
POJO |
JSON String |
ignored |
application/json |
|
Tuple |
JSON String |
ignored |
application/json |
JSON is tailored for Tuple |
POJO |
String (toString()) |
ignored |
text/plain, java.lang.String |
|
POJO |
byte[] (java.io serialized) |
ignored |
application/x-java-serialized-object |
|
JSON byte[] or String |
POJO |
application/json (or none) |
application/x-java-object |
|
byte[] or String |
Serializable |
application/x-java-serialized-object |
application/x-java-object |
|
JSON byte[] or String |
Tuple |
application/json (or none) |
application/x-spring-tuple |
|
byte[] |
String |
any |
text/plain, java.lang.String |
will apply any Charset specified in the content-type header |
String |
byte[] |
any |
application/octet-stream |
will apply any Charset specified in the content-type header |
Conversion applies to payloads that require type conversion. For example, if a module produces an XML string with outputType=application/json, the payload will not be converted from XML to JSON. This is because the payload at the module’s output channel is already a String so no conversion will be applied at runtime.
While conversion is supported for both input and output channels, it is especially recommended to be used for the conversion of outbound messages.
For the conversion of inbound messages, especially when the target is a POJO, the @StreamListener support will perform the conversion automatically.
@StreamListener and Message ConversionThe @StreamListener annotation provides a convenient way for converting incoming messages without the need to specify the content type of an input channel.
During the dispatching process to methods annotated with @StreamListener, a conversion will be applied automatically if the argument requires it.
For example, let’s consider a message with the String content {"greeting":"Hello, world"} and a content-type header of application/json is received on the input channel.
Let us consider the following application that receives it:
public class GreetingMessage {
String greeting;
public String getGreeting() {
return greeting;
}
public void setGreeting(String greeting) {
this.greeting = greeting;
}
}
@EnableBinding(Sink.class)
@EnableAutoConfiguration
public static class GreetingSink {
@StreamListener(Sink.INPUT)
public void receive(Greeting greeting) {
// handle Greeting
}
}
The argument of the method will be populated automatically with the POJO containing the unmarshalled form of the JSON String.
While Spring Cloud Stream makes it easy for individual Spring Boot applications to connect to messaging systems, the typical scenario for Spring Cloud Stream is the creation of multi-application pipelines, where microservice applications send data to each other. You can achieve this scenario by correlating the input and output destinations of adjacent applications.
Supposing that a design calls for the Time Source application to send data to the Log Sink application, you can use a common destination named ticktock for bindings within both applications.
Time Source will set the following property:
spring.cloud.stream.bindings.output.destination=ticktock
Log Sink will set the following property:
spring.cloud.stream.bindings.input.destination=ticktock
When scaling up Spring Cloud Stream applications, each instance can receive information about how many other instances of the same application exist and what its own instance index is.
Spring Cloud Stream does this through the spring.cloud.stream.instanceCount and spring.cloud.stream.instanceIndex properties.
For example, if there are three instances of a HDFS sink application, all three instances will have spring.cloud.stream.instanceCount set to 3, and the individual applications will have spring.cloud.stream.instanceIndex set to 0, 1, and 2, respectively.
When Spring Cloud Stream applications are deployed via Spring Cloud Data Flow, these properties are configured automatically; when Spring Cloud Stream applications are launched independently, these properties must be set correctly.
By default, spring.cloud.stream.instanceCount is 1, and spring.cloud.stream.instanceIndex is 0.
In a scaled-up scenario, correct configuration of these two properties is important for addressing partitioning behavior (see below) in general, and the two properties are always required by certain binders (e.g., the Kafka binder) in order to ensure that data are split correctly across multiple consumer instances.
An output binding is configured to send partitioned data by setting one and only one of its partitionKeyExpression or partitionKeyExtractorClass properties, as well as its partitionCount property.
For example, the following is a valid and typical configuration:
spring.cloud.stream.bindings.output.producer.partitionKeyExpression=payload.id spring.cloud.stream.bindings.output.producer.partitionCount=5
Based on the above example configuration, data will be sent to the target partition using the following logic.
A partition key’s value is calculated for each message sent to a partitioned output channel based on the partitionKeyExpression.
The partitionKeyExpression is a SpEL expression which is evaluated against the outbound message for extracting the partitioning key.
|
Tip
|
If a SpEL expression is not sufficient for your needs, you can instead calculate the partition key value by setting the property |
Once the message key is calculated, the partition selection process will determine the target partition as a value between 0 and partitionCount - 1.
The default calculation, applicable in most scenarios, is based on the formula key.hashCode() % partitionCount.
This can be customized on the binding, either by setting a SpEL expression to be evaluated against the key (via the partitionSelectorExpression property) or by setting a org.springframework.cloud.stream.binder.PartitionSelectorStrategy implementation (via the partitionSelectorClass property).
Additional properties can be configured for more advanced scenarios, as described in the following section.
|
Note
|
The Kafka binder will use the |
An input binding is configured to receive partitioned data by setting its partitioned property, as well as the instanceIndex and instanceCount properties on the application itself, as in the following example:
spring.cloud.stream.bindings.input.consumer.partitioned=true spring.cloud.stream.instanceIndex=3 spring.cloud.stream.instanceCount=5
The instanceCount value represents the total number of application instances between which the data need to be partitioned, and the instanceIndex must be a unique value across the multiple instances, between 0 and instanceCount - 1.
The instance index helps each application instance to identify the unique partition (or, in the case of Kafka, the partition set) from which it receives data.
It is important to set both values correctly in order to ensure that all of the data is consumed and that the application instances receive mutually exclusive datasets.
While a scenario which using multiple instances for partitioned data processing may be complex to set up in a standalone case, Spring Cloud Dataflow can simplify the process significantly by populating both the input and output values correctly as well as relying on the runtime infrastructure to provide information about the instance index and instance count.
Spring Cloud Stream provides support for testing your microservice applications without connecting to a messaging system.
You can do that by using the TestSupportBinder.
This is useful especially for unit testing your microservices.
The TestSupportBinder allows users to interact with the bound channels and inspect what messages are sent and received by the application
For outbound message channels, the TestSupportBinder registers a single subscriber and retains the messages emitted by the application in a MessageCollector.
They can be retrieved during tests and have assertions made against them.
The user can also send messages to inbound message channels, so that the consumer application can consume the messages. The following example shows how to test both input and output channels on a processor.
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = ExampleTest.MyProcessor.class)
@IntegrationTest({"server.port=-1"})
@DirtiesContext
public class ExampleTest {
@Autowired
private Processor processor;
@Autowired
private BinderFactory<MessageChannel> binderFactory;
@Autowired
private MessageCollector messageCollector;
@Test
@SuppressWarnings("unchecked")
public void testWiring() {
Message<String> message = new GenericMessage<>("hello");
processor.input().send(message);
Message<String> received = (Message<String>) messageCollector.forChannel(processor.output()).poll();
assertThat(received.getPayload(), equalTo("hello world"));
}
@SpringBootApplication
@EnableBinding(Processor.class)
public static class MyProcessor {
@Autowired
private Processor channels;
@Transformer(inputChannel = Processor.INPUT, outputChannel = Processor.OUTPUT)
public String transform(String in) {
return in + " world";
}
}
}
In the example above, we are creating an application that has an input and an output channel, bound through the Processor interface.
The bound interface is injected into the test so we can have access to both channels.
We are sending a message on the input channel and we are using the MessageCollector provided by Spring Cloud Stream’s test support to capture the message has been sent to the output channel as a result.
Once we have received the message, we can validate that the component functions correctly.
Spring Cloud Stream provides a health indicator for binders.
It is registered under the name of binders and can be enabled or disabled by setting the management.health.binders.enabled property.
For Spring Cloud Stream samples, please refer to the spring-cloud-stream-samples repository on GitHub.
To get started with creating Spring Cloud Stream applications, visit the Spring Initializr and create a new Maven project named "GreetingSource". Select Spring Boot version 1.3.4 SNAPSHOT and search or tick the checkbox for Stream Kafka (we will be using Kafka for messaging).
Next, create a new class, GreetingSource, in the same package as the GreetingSourceApplication class.
Give it the following code:
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.messaging.Source;
import org.springframework.integration.annotation.InboundChannelAdapter;
@EnableBinding(Source.class)
public class GreetingSource {
@InboundChannelAdapter(Source.OUTPUT)
public String greet() {
return "hello world " + System.currentTimeMillis();
}
}
The @EnableBinding annotation is what triggers the creation of Spring Integration infrastructure components.
Specifically, it will create a Kafka connection factory, a Kafka outbound channel adapter, and the message channel defined inside the Source interface:
public interface Source {
String OUTPUT = "output";
@Output(Source.OUTPUT)
MessageChannel output();
}
The auto-configuration also creates a default poller, so that the greet() method will be invoked once per second.
The standard Spring Integration @InboundChannelAdapter annotation sends a message to the source’s output channel, using the return value as the payload of the message.
To test-drive this setup, run a Kafka message broker. An easy way to do this is to use a Docker image:
# On OS X
$ docker run -p 2181:2181 -p 9092:9092 --env ADVERTISED_HOST=`docker-machine ip \`docker-machine active\`` --env ADVERTISED_PORT=9092 spotify/kafka
# On Linux
$ docker run -p 2181:2181 -p 9092:9092 --env ADVERTISED_HOST=localhost --env ADVERTISED_PORT=9092 spotify/kafka
Build the application:
./mvnw clean package
The consumer application is coded in a similar manner.
Go back to Initializr and create another project, named LoggingSink.
Then create a new class, LoggingSink, in the same package as the class LoggingSinkApplication and with the following code:
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.cloud.stream.messaging.Sink;
@EnableBinding(Sink.class)
public class LoggingSink {
@StreamListener(Sink.INPUT)
public void log(String message) {
System.out.println(message);
}
}
Build the application:
./mvnw clean package
To connect the GreetingSource application to the LoggingSink application, each application must share the same destination name. Starting up both applications as shown below, you will see the consumer application printing "hello world" and a timestamp to the console:
cd GreetingSource
java -jar target/GreetingSource-0.0.1-SNAPSHOT.jar --spring.cloud.stream.bindings.output.destination=mydest
cd LoggingSink
java -jar target/LoggingSink-0.0.1-SNAPSHOT.jar --server.port=8090 --spring.cloud.stream.bindings.input.destination=mydest
(The different server port prevents collisions of the HTTP port used to service the Spring Boot Actuator endpoints in the two applications.)
The output of the LoggingSink application will look something like the following:
[ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8090 (http)
[ main] com.example.LoggingSinkApplication : Started LoggingSinkApplication in 6.828 seconds (JVM running for 7.371)
hello world 1458595076731
hello world 1458595077732
hello world 1458595078733
hello world 1458595079734
hello world 1458595080735
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 or spring-cloud-starter-bus-kafka to your dependency management and Spring Cloud takes care of the rest. Make sure the broker (RabbitMQ or Kafka) is available and configured: 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. for Rabbit
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 may be added in the future (ie. only service X nodes in data center Y, etc…). There are also some http endpoints under the /bus/* actuator namespace. There are currently two implemented. The first, /bus/env, sends key/value pairs to update each node’s Spring Environment. The second, /bus/refresh, will reload each application’s configuration, just as if they had all been pinged on their /refresh endpoint.
|
Note
|
The Bus starters cover Rabbit and Kafka, because those are the two most common implementations, but Spring Cloud Stream is quite flexible and binder will work combined with spring-cloud-bus.
|
The HTTP endpoints accept a "destination" parameter, e.g. "/bus/refresh?destination=customers:9000", where the destination is an ApplicationContext ID. If the ID is owned by an instance on the Bus then it will process the message and all other instances will ignore it. Spring Boot sets the ID for you in the ContextIdApplicationContextInitializer to a combination of the spring.application.name, active profiles and server.port by default.
The "destination" parameter is used in a Spring PathMatcher (with the path separator as a colon :) to determine if an instance will process the message. Using the example from above, "/bus/refresh?destination=customers:**" will target all instances of the "customers" service regardless of the profiles and ports set as the ApplicationContext ID.
The bus tries to eliminate processing an event twice, once from the original ApplicationEvent and once from the queue. To do this, it checks the sending application context id againts the current application context id. If multiple instances of a service have the same application context id, events will not be processed. Running on a local machine, each service will be on a different port and that will be part of the application context id. Cloud Foundry supplies an index to differentiate. To ensure that the application context id is the unique, set spring.application.index to something unique for each instance of a service. For example, in lattice, set spring.application.index=${INSTANCE_INDEX} in application.properties (or bootstrap.properties if using configserver).
Spring Cloud Bus uses
Spring Cloud Stream to
broadcast the messages so to get messages to flow you only need to
include the binder implementation of your choice in the
classpath. There are convenient starters specifically for the bus with
AMQP (RabbitMQ) and Kafka
(spring-cloud-starter-bus-[amqp,kafka]). Generally speaking
Spring Cloud Stream relies on Spring Boot autoconfiguration
conventions for configuring middleware, so for instance the AMQP
broker address can be changed with spring.rabbitmq.*
configuration properties. Spring Cloud Bus has a handful of native
configuration properties in spring.cloud.bus.*
(e.g. spring.cloud.bus.destination is the name of the topic to use
the the externall middleware). Normally the defaults will suffice.
To lean more about how to customize the message broker settings consult the Spring Cloud Stream documentation.
Bus events (subclasses of RemoteApplicationEvent) can be traced by
setting spring.cloud.bus.trace.enabled=true. If you do this then the
Spring Boot TraceRepository (if it is present) will show each event
sent and all the acks from each service instance. Example (from the
/trace endpoint):
{
"timestamp": "2015-11-26T10:24:44.411+0000",
"info": {
"signal": "spring.cloud.bus.ack",
"type": "RefreshRemoteApplicationEvent",
"id": "c4d374b7-58ea-4928-a312-31984def293b",
"origin": "stores:8081",
"destination": "*:**"
}
},
{
"timestamp": "2015-11-26T10:24:41.864+0000",
"info": {
"signal": "spring.cloud.bus.sent",
"type": "RefreshRemoteApplicationEvent",
"id": "c4d374b7-58ea-4928-a312-31984def293b",
"origin": "customers:9000",
"destination": "*:**"
}
},
{
"timestamp": "2015-11-26T10:24:41.862+0000",
"info": {
"signal": "spring.cloud.bus.ack",
"type": "RefreshRemoteApplicationEvent",
"id": "c4d374b7-58ea-4928-a312-31984def293b",
"origin": "customers:9000",
"destination": "*:**"
}
}
This trace shows that a RefreshRemoteApplicationEvent was sent from
customers:9000, broadcast to all services, and it was received
(acked) by customers:9000 and stores:8081.
To handle the ack signals yourself you could add an @EventListener
for the AckRemoteApplicationEvent and SentApplicationEvent types
to your app (and enable tracing). Or you could tap into the
TraceRepository and mine the data from there.
|
Note
|
Any Bus application can trace acks, but sometimes it will be useful to do this in a central service that can do more complex queries on the data. Or forward it to a specialized tracing service. |
The Bus can carry any event of type RemoteApplicationEvent, but the
default transport is JSON and the deserializer needs to know which
types are going to be used ahead of time. To register a new type it
needs to be in a subpackage of org.springframework.cloud.bus.event.
You can use @JsonTypeName on your custom class or rely on the
default strategy which is to use the simple name of the class. Note
that both the producer and the consumer will need access to the class
definition.
Adrian Cole, Spencer Gibb, Marcin Grzejszczak, Dave Syer
Brixton.BUILD-SNAPSHOT
Spring Cloud Sleuth implements a distributed tracing solution for Spring Cloud.
Spring Cloud Sleuth borrows Dapper’s terminology.
Span: The basic unit of work. For example, sending an RPC is a new span, as is sending a response to an RPC. Span’s are identified by a unique 64-bit ID for the span and another 64-bit ID for the trace the span is a part of. Spans also have other data, such as descriptions, timestamped events, key-value annotations (tags), the ID of the span that caused them, and process ID’s (normally IP address).
Spans are started and stopped, and they keep track of their timing information. Once you create a span, you must stop it at some point in the future.
|
Tip
|
The initial span that starts a trace is called a root span. The value of span id
of that span is equal to trace id.
|
Trace: A set of spans forming a tree-like structure. For example, if you are running a distributed big-data store, a trace might be formed by a put request.
Annotation: is used to record existence of an event in time. Some of the core annotations used to define the start and stop of a request are:
cs - Client Sent - The client has made a request. This annotation depicts the start of the span.
sr - Server Received - The server side got the request and will start processing it. If one subtracts the cs timestamp from this timestamp one will receive the network latency.
ss - Server Sent - Annotated upon completion of request processing (when the response got sent back to the client). If one subtracts the sr timestamp from this timestamp one will receive the time needed by the server side to process the request.
cr - Client Received - Signifies the end of the span. The client has successfully received the response from the server side. If one subtracts the cs timestamp from this timestamp one will receive the whole time needed by the client to receive the response from the server.
Visualization of what Span and Trace will look in a system together with the Zipkin annotations:
Each color of a note signifies a span (7 spans - from A to G). If you have such information in the note:
Trace Id = X
Span Id = D
Client Sent
That means that the current span has Trace-Id set to X, Span-Id set to D. It also has emitted Client Sent event.
This is how the visualization of the parent / child relationship of spans would look like:
In the following sections the example from the image above will be taken into consideration.
Altogether there are 7 spans . If you go to traces in Zipkin you will see this number in the second trace:
However if you pick a particular trace then you will see 4 spans:
|
Note
|
When picking a particular trace you will see merged spans. That means that if there were 2 spans sent to Zipkin with Server Received and Server Sent / Client Received and Client Sent annotations then they will presented as a single span. |
Why is there a difference between the 7 and 4 spans in this case?
2 spans come from http:/start span. It has the Server Received (SR) and Server Sent (SS) annotations.
2 spans come from the RPC call from service1 to service2 to the http:/foo endpoint. It has the Client Sent (CS)
and Client Received (CR) annotations on service1 side. It also has Server Received (SR) and Server Sent (SS) annotations
on the service2 side. Physically there are 2 spans but they form 1 logical span related to an RPC call.
2 spans come from the RPC call from service2 to service3 to the http:/bar endpoint. It has the Client Sent (CS)
and Client Received (CR) annotations on service2 side. It also has Server Received (SR) and Server Sent (SS) annotations
on the service3 side. Physically there are 2 spans but they form 1 logical span related to an RPC call.
2 spans come from the RPC call from service2 to service4 to the http:/baz endpoint. It has the Client Sent (CS)
and Client Received (CR) annotations on service2 side. It also has Server Received (SR) and Server Sent (SS) annotations
on the service4 side. Physically there are 2 spans but they form 1 logical span related to an RPC call.
So if we count the physical spans we have 1 from http:/start, 2 from service1 calling service2, 2 form service2
calling service3 and 2 from service2 calling service4. Altogether 7 spans.
Logically we see the information of Total Spans: 4 because we have 1 span related to the incoming request
to service1 and 3 spans related to RPC calls.
Zipkin allows you to visualize errors in your trace. When an exception was thrown and wasn’t caught then we’re setting proper tags on the span which Zipkin can properly colorize. You could see in the list of traces one trace that was in red color. That’s because there was an exception thrown.
If you click that trace then you’ll see a similar picture
Then if you click on one of the spans you’ll see the following
As you can see you can easily see the reason for an error and the whole stacktrace related to it.
The dependency graph in Zipkin would look like this:
When grepping the logs of those four applications by trace id equal to e.g. 2485ec27856c56f4 one would get the following:
service1.log:2016-02-26 11:15:47.561 INFO [service1,2485ec27856c56f4,2485ec27856c56f4,true] 68058 --- [nio-8081-exec-1] i.s.c.sleuth.docs.service1.Application : Hello from service1. Calling service2
service2.log:2016-02-26 11:15:47.710 INFO [service2,2485ec27856c56f4,9aa10ee6fbde75fa,true] 68059 --- [nio-8082-exec-1] i.s.c.sleuth.docs.service2.Application : Hello from service2. Calling service3 and then service4
service3.log:2016-02-26 11:15:47.895 INFO [service3,2485ec27856c56f4,1210be13194bfe5,true] 68060 --- [nio-8083-exec-1] i.s.c.sleuth.docs.service3.Application : Hello from service3
service2.log:2016-02-26 11:15:47.924 INFO [service2,2485ec27856c56f4,9aa10ee6fbde75fa,true] 68059 --- [nio-8082-exec-1] i.s.c.sleuth.docs.service2.Application : Got response from service3 [Hello from service3]
service4.log:2016-02-26 11:15:48.134 INFO [service4,2485ec27856c56f4,1b1845262ffba49d,true] 68061 --- [nio-8084-exec-1] i.s.c.sleuth.docs.service4.Application : Hello from service4
service2.log:2016-02-26 11:15:48.156 INFO [service2,2485ec27856c56f4,9aa10ee6fbde75fa,true] 68059 --- [nio-8082-exec-1] i.s.c.sleuth.docs.service2.Application : Got response from service4 [Hello from service4]
service1.log:2016-02-26 11:15:48.182 INFO [service1,2485ec27856c56f4,2485ec27856c56f4,true] 68058 --- [nio-8081-exec-1] i.s.c.sleuth.docs.service1.Application : Got response from service2 [Hello from service2, response from service3 [Hello from service3] and from service4 [Hello from service4]]
If you’re using a log aggregating tool like Kibana, Splunk etc. you can order the events that took place. An example of Kibana would look like this:
If you want to use Logstash here is the Grok pattern for Logstash:
filter {
# pattern matching logback pattern
grok {
match => { "message" => "%{TIMESTAMP_ISO8601:timestamp}\s+%{LOGLEVEL:severity}\s+\[%{DATA:service},%{DATA:trace},%{DATA:span},%{DATA:exportable}\]\s+%{DATA:pid}---\s+\[%{DATA:thread}\]\s+%{DATA:class}\s+:\s+%{GREEDYDATA:rest}" }
}
}
|
Note
|
If you want to use Grok together with the logs from Cloud Foundry you have to use this pattern: |
filter {
# pattern matching logback pattern
grok {
match => { "message" => "(?m)OUT\s+%{TIMESTAMP_ISO8601:timestamp}\s+%{LOGLEVEL:severity}\s+\[%{DATA:service},%{DATA:trace},%{DATA:span},%{DATA:exportable}\]\s+%{DATA:pid}---\s+\[%{DATA:thread}\]\s+%{DATA:class}\s+:\s+%{GREEDYDATA:rest}" }
}
}
Often you do not want to store your logs in a text file but in a JSON file that Logstash can immediately pick. To do that you have to do the following (for readability
we’re passing the dependencies in the groupId:artifactId:version notation.
Dependencies setup
Ensure that Logback is on the classpath (ch.qos.logback:logback-core)
Add Logstash Logback encode - example for version 4.6 : net.logstash.logback:logstash-logback-encoder:4.6
Logback setup
Below you can find an example of a Logback configuration (file named logback-spring.xml) that:
logs information from the application in a JSON format to a build/${spring.application.name}.json file
has commented out two additional appenders - console and standard log file
has the same logging pattern as the one presented in the previous section
|
Note
|
If you’re using a custom logback-spring.xml then you have to pass the spring.application.name in
bootstrap instead of application property file. Otherwise your custom logback file won’t read the property properly.
|
If you want to profit only from Spring Cloud Sleuth without the Zipkin integration just add
the spring-cloud-starter-sleuth module to your project.
<dependencyManagement> (1)
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Brixton.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependency> (2)
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-sleuth</artifactId>
</dependency>
In order not to pick versions by yourself it’s much better if you add the dependency management via the Spring BOM
Add the dependency to spring-cloud-starter-sleuth
dependencyManagement { (1)
imports {
mavenBom "org.springframework.cloud:spring-cloud-dependencies:Brixton.RELEASE"
}
}
dependencies { (2)
compile "org.springframework.cloud:spring-cloud-starter-sleuth"
}
In order not to pick versions by yourself it’s much better if you add the dependency management via the Spring BOM
Add the dependency to spring-cloud-starter-sleuth
If you want both Sleuth and Zipkin just add the spring-cloud-starter-zipkin dependency.
<dependencyManagement> (1)
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Brixton.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependency> (2)
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zipkin</artifactId>
</dependency>
In order not to pick versions by yourself it’s much better if you add the dependency management via the Spring BOM
Add the dependency to spring-cloud-starter-zipkin
dependencyManagement { (1)
imports {
mavenBom "org.springframework.cloud:spring-cloud-dependencies:Brixton.RELEASE"
}
}
dependencies { (2)
compile "org.springframework.cloud:spring-cloud-starter-zipkin"
}
In order not to pick versions by yourself it’s much better if you add the dependency management via the Spring BOM
Add the dependency to spring-cloud-starter-zipkin
If you want both Sleuth and Zipkin just add the spring-cloud-sleuth-stream dependency.
<dependencyManagement> (1)
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Brixton.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependency> (2)
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-sleuth-stream</artifactId>
</dependency>
<dependency> (3)
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-sleuth</artifactId>
</dependency>
<!-- EXAMPLE FOR RABBIT BINDING -->
<dependency> (4)
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-stream-binder-rabbit</artifactId>
</dependency>
In order not to pick versions by yourself it’s much better if you add the dependency management via the Spring BOM
Add the dependency to spring-cloud-sleuth-stream
Add the dependency to spring-cloud-starter-sleuth - that way all dependant dependencies will be downloaded
Add a binder (e.g. Rabbit binder) to tell Spring Cloud Stream what it should bind to
dependencyManagement { (1)
imports {
mavenBom "org.springframework.cloud:spring-cloud-dependencies:Brixton.RELEASE"
}
}
dependencies {
compile "org.springframework.cloud:spring-cloud-sleuth-stream" (2)
compile "org.springframework.cloud:spring-cloud-starter-sleuth" (3)
// Example for Rabbit binding
compile "org.springframework.cloud:spring-cloud-stream-binder-rabbit" (4)
}
In order not to pick versions by yourself it’s much better if you add the dependency management via the Spring BOM
Add the dependency to spring-cloud-sleuth-stream
Add the dependency to spring-cloud-starter-sleuth - that way all dependant dependencies will be downloaded
Add a binder (e.g. Rabbit binder) to tell Spring Cloud Stream what it should bind to
If you want to start a Spring Cloud Sleuth Stream Zipkin collector just add the spring-cloud-sleuth-zipkin-stream
dependency
<dependencyManagement> (1)
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Brixton.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependency> (2)
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-sleuth-zipkin-stream</artifactId>
</dependency>
<dependency> (3)
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-sleuth</artifactId>
</dependency>
<!-- EXAMPLE FOR RABBIT BINDING -->
<dependency> (4)
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-stream-binder-rabbit</artifactId>
</dependency>
In order not to pick versions by yourself it’s much better if you add the dependency management via the Spring BOM
Add the dependency to spring-cloud-sleuth-zipkin-stream
Add the dependency to spring-cloud-starter-sleuth - that way all dependant dependencies will be downloaded
Add a binder (e.g. Rabbit binder) to tell Spring Cloud Stream what it should bind to
dependencyManagement { (1)
imports {
mavenBom "org.springframework.cloud:spring-cloud-dependencies:Brixton.RELEASE"
}
}
dependencies {
compile "org.springframework.cloud:spring-cloud-sleuth-zipkin-stream" (2)
compile "org.springframework.cloud:spring-cloud-starter-sleuth" (3)
// Example for Rabbit binding
compile "org.springframework.cloud:spring-cloud-stream-binder-rabbit" (4)
}
In order not to pick versions by yourself it’s much better if you add the dependency management via the Spring BOM
Add the dependency to spring-cloud-sleuth-zipkin-stream
Add the dependency to spring-cloud-starter-sleuth - that way all dependant dependencies will be downloaded
Add a binder (e.g. Rabbit binder) to tell Spring Cloud Stream what it should bind to
and then just annotate your main class with @EnableZipkinStreamServer annotation:
Adds trace and span ids to the Slf4J MDC, so you can extract all the logs from a given trace or span in a log aggregator. Example logs:
2016-02-02 15:30:57.902 INFO [bar,6bfd228dc00d216b,6bfd228dc00d216b,false] 23030 --- [nio-8081-exec-3] ... 2016-02-02 15:30:58.372 ERROR [bar,6bfd228dc00d216b,6bfd228dc00d216b,false] 23030 --- [nio-8081-exec-3] ... 2016-02-02 15:31:01.936 INFO [bar,46ab0d418373cbc9,46ab0d418373cbc9,false] 23030 --- [nio-8081-exec-4] ...
notice the [appname,traceId,spanId,exportable] entries from the MDC:
spanId - the id of a specific operation that took place
appname - the name of the application that logged the span
traceId - the id of the latency graph that contains the span
exportable - whether the log should be exported to Zipkin or not. When would you like the span not to be exportable? In the case in which you want to wrap some operation in a Span and have it written to the logs only.
Provides an abstraction over common distributed tracing data models: traces, spans (forming a DAG), annotations, key-value annotations. Loosely based on HTrace, but Zipkin (Dapper) compatible.
Sleuth records timing information to aid in latency analysis. Using sleuth, you can pinpoint causes of latency in your applications. Sleuth is written to not log too much, and to not cause your production application to crash.
propagates structural data about your call-graph in-band, and the rest out-of-band.
includes opinionated instrumentation of layers such as HTTP
includes sampling policy to manage volume
can report to a Zipkin system for query and visualization
Instruments common ingress and egress points from Spring applications (servlet filter, async endpoints, rest template, scheduled actions, message channels, zuul filters, feign client).
Sleuth includes default logic to join a trace across http or messaging boundaries. For example, http propagation
works via Zipkin-compatible request headers. This propagation logic is defined and customized via
SpanInjector and SpanExtractor implementations.
Provides simple metrics of accepted / dropped spans.
If spring-cloud-sleuth-zipkin then the app will generate and collect Zipkin-compatible traces.
By default it sends them via HTTP to a Zipkin server on localhost (port 9411).
Configure the location of the service using spring.zipkin.baseUrl.
If spring-cloud-sleuth-stream then the app will generate and collect traces via Spring Cloud Stream.
Your app automatically becomes a producer of tracer messages that are sent over your broker of choice
(e.g. RabbitMQ, Apache Kafka, Redis).
|
Important
|
If using Zipkin or Stream, configure the percentage of spans exported using spring.sleuth.sampler.percentage
(default 0.1, i.e. 10%). Otherwise you might think that Sleuth is not working cause it’s omitting some spans.
|
|
Note
|
the SLF4J MDC is always set and logback users will immediately see the trace and span ids in logs per the example
above. Other logging systems have to configure their own formatter to get the same result. The default is
logging.pattern.level set to %clr(%5p) %clr([${spring.application.name:},%X{X-B3-TraceId:-},%X{X-B3-SpanId:-},%X{X-Span-Export:-}]){yellow}
(this is a Spring Boot feature for logback users).
This means that if you’re not using SLF4J this pattern WILL NOT be automatically applied.
|
In distributed tracing the data volumes can be very high so sampling
can be important (you usually don’t need to export all spans to get a
good picture of what is happening). Spring Cloud Sleuth has a
Sampler strategy that you can implement to take control of the
sampling algorithm. Samplers do not stop span (correlation) ids from
being generated, but they do prevent the tags and events being
attached and exported. By default you get a strategy that continues to
trace if a span is already active, but new ones are always marked as
non-exportable. If all your apps run with this sampler you will see
traces in logs, but not in any remote store. For testing the default
is often enough, and it probably is all you need if you are only using
the logs (e.g. with an ELK aggregator). If you are exporting span data
to Zipkin or Spring Cloud Stream, there is also an AlwaysSampler
that exports everything and a PercentageBasedSampler that samples a
fixed fraction of spans.
|
Note
|
the PercentageBasedSampler is the default if you are using
spring-cloud-sleuth-zipkin or spring-cloud-sleuth-stream. You can
configure the exports using spring.sleuth.sampler.percentage. The passed
value needs to be a double from 0.0 to 1.0 so it’s not a percentage.
For backwards compatibility reasons we’re not changing the property name.
|
A sampler can be installed just by creating a bean definition, e.g:
@Bean
public Sampler defaultSampler() {
return new AlwaysSampler();
}
Spring Cloud Sleuth instruments all your Spring application
automatically, so you shouldn’t have to do anything to activate
it. The instrumentation is added using a variety of technologies
according to the stack that is available, e.g. for a servlet web
application we use a Filter, and for Spring Integration we use
ChannelInterceptors.
You can customize the keys used in span tags. To limit the volume of
span data, by default an HTTP request will be tagged only with a
handful of metadata like the status code, host and URL. You can add
request headers by configuring spring.sleuth.keys.http.headers (a
list of header names).
|
Note
|
Remember that tags are only collected and exported if there is a
Sampler that allows it (by default there is not, so there is no
danger of accidentally collecting too much data without configuring
something).
|
|
Note
|
Currently the instrumentation in Spring Cloud Sleuth is eager - it means that we’re actively trying to pass the tracing context between threads. Also timing events are captured even when sleuth isn’t exporting data to a tracing system. This approach may change in the future towards being lazy on this matter. |
You can do the following operations on the Span by means of org.springframework.cloud.sleuth.Tracer interface:
start - when you start a span its name is assigned and start timestamp is recorded.
close - the span gets finished (the end time of the span is recorded) and if the span is exportable then it will be eligible for collection to Zipkin. The span is also removed from the current thread.
continue - a new instance of span will be created whereas it will be a copy of the one that it continues.
detach - the span doesn’t get stopped or closed. It only gets removed from the current thread.
create with explicit parent - you can create a new span and set an explicit parent to it
|
Tip
|
Spring creates the instance of Tracer for you. In order to use it all you need is to just autowire it.
|
You can manually create spans by using the Tracer interface.
// Start a span. If there was a span present in this thread it will become
// the `newSpan`'s parent.
Span newSpan = this.tracer.createSpan("calculateTax");
try {
// ...
// You can tag a span
this.tracer.addTag("taxValue", taxValue);
// ...
// You can log an event on a span
newSpan.logEvent("taxCalculated");
} finally {
// Once done remember to close the span. This will allow collecting
// the span to send it to Zipkin
this.tracer.close(newSpan);
}
In this example we could see how to create a new instance of span. Assuming that there already was a span present in this thread then it would become the parent of that span.
|
Important
|
Always clean after you create a span! Don’t forget to close a span if you want to send it to Zipkin. |
Sometimes you don’t want to create a new span but you want to continue one. Example of such a situation might be (of course it all depends on the use-case):
AOP - If there was already a span created before an aspect was reached then you might not want to create a new span.
Hystrix - executing a Hystrix command is most likely a logical part of the current processing. It’s in fact only a technical implementation detail that you wouldn’t necessarily want to reflect in tracing as a separate being.
The continued instance of span is equal to the one that it continues:
Span continuedSpan = this.tracer.continueSpan(spanToContinue);
assertThat(continuedSpan).isEqualTo(spanToContinue);
To continue a span you can use the Tracer interface.
// let's assume that we're in a thread Y and we've received
// the `initialSpan` from thread X
Span continuedSpan = this.tracer.continueSpan(initialSpan);
try {
// ...
// You can tag a span
this.tracer.addTag("taxValue", taxValue);
// ...
// You can log an event on a span
continuedSpan.logEvent("taxCalculated");
} finally {
// Once done remember to detach the span. That way you'll
// safely remove it from the current thread without closing it
this.tracer.detach(continuedSpan);
}
|
Important
|
Always clean after you create a span! Don’t forget to detach a span if some work was done started in one thread (e.g. thread X) and it’s waiting for other threads (e.g. Y, Z) to finish. Then the spans in the threads Y, Z should be detached at the end of their work. When the results are collected the span in thread X should be closed. |
There is a possibility that you want to start a new span and provide an explicit parent of that span.
Let’s assume that the parent of a span is in one thread and you want to start a new span in another thread. The
startSpan method of the Tracer interface is the method you are looking for.
// let's assume that we're in a thread Y and we've received
// the `initialSpan` from thread X. `initialSpan` will be the parent
// of the `newSpan`
Span newSpan = this.tracer.createSpan("calculateCommission", initialSpan);
try {
// ...
// You can tag a span
this.tracer.addTag("commissionValue", commissionValue);
// ...
// You can log an event on a span
newSpan.logEvent("commissionCalculated");
} finally {
// Once done remember to close the span. This will allow collecting
// the span to send it to Zipkin. The tags and events set on the
// newSpan will not be present on the parent
this.tracer.close(newSpan);
}
|
Important
|
After having created such a span remember to close it. Otherwise you will see a lot of warnings in your logs related to the fact that you have a span present in the current thread other than the one you’re trying to close. What’s worse your spans won’t get closed properly thus will not get collected to Zipkin. |
Picking a span name is not a trivial task. Span name should depict an operation name. The name should be low cardinality (e.g. not include identifiers).
Since there is a lot of instrumentation going on some of the span names will be artificial like:
controller-method-name when received by a Controller with a method name conrollerMethodName
async for asynchronous operations done via wrapped Callable and Runnable.
@Scheduled annotated methods will return the simple name of the class.
Fortunately, for the asynchronous processing you can provide explicit naming.
You can do name the span explicitly via the @SpanName annotation.
@SpanName("calculateTax")
class TaxCountingRunnable implements Runnable {
@Override public void run() {
// perform logic
}
}
In this case, when processed in the following manner:
Runnable runnable = new TraceRunnable(tracer, spanNamer, new TaxCountingRunnable());
Future<?> future = executorService.submit(runnable);
// ... some additional logic ...
future.get();
The span will be named calculateTax.
It’s pretty rare to create separate classes for Runnable or Callable. Typically one creates an anonymous
instance of those classes. You can’t annotate such classes thus to override that, if there is no @SpanName annotation present,
we’re checking if the class has a custom implementation of the toString() method.
So executing such code:
Runnable runnable = new TraceRunnable(tracer, spanNamer, new Runnable() {
@Override public void run() {
// perform logic
}
@Override public String toString() {
return "calculateTax";
}
});
Future<?> future = executorService.submit(runnable);
// ... some additional logic ...
future.get();
will lead in creating a span named calculateTax.
Thanks to the SpanInjector and SpanExtractor you can customize the way spans
are created and propagated.
There are currently two built-in ways to pass tracing information between processes:
via Spring Integration
via HTTP
Span ids are extracted from Zipkin-compatible (B3) headers (either Message
or HTTP headers), to start or join an existing trace. Trace information is
injected into any outbound requests so the next hop can extract them.
For Spring Integration these are the beans responsible for creation of a Span from a Message
and filling in the MessageBuilder with tracing information.
@Bean
public SpanExtractor<Message> messagingSpanExtractor() {
...
}
@Bean
public SpanInjector<MessageBuilder> messagingSpanInjector() {
...
}
You can override them by providing your own implementation and by adding a @Primary annotation
to your bean definition.
For HTTP these are the beans responsible for creation of a Span from a HttpServletRequest.
@Bean
public SpanExtractor<HttpServletRequest> httpServletRequestSpanExtractor() {
...
}
You can override them by providing your own implementation and by adding a @Primary annotation
to your bean definition.
Let’s assume that instead of the standard Zipkin compatible tracing HTTP header names you have
for trace id - correlationId
for span id - mySpanId
This is a an example of a SpanExtractor
static class CustomHttpServletRequestSpanExtractor
implements SpanExtractor<HttpServletRequest> {
@Override
public Span joinTrace(HttpServletRequest carrier) {
long traceId = Span.hexToId(carrier.getHeader("correlationId"));
long spanId = Span.hexToId(carrier.getHeader("mySpanId"));
// extract all necessary headers
Span.SpanBuilder builder = Span.builder().traceId(traceId).spanId(spanId);
// build rest of the Span
return builder.build();
}
}
And you could register it like this:
@Bean
@Primary
SpanExtractor<HttpServletRequest> customHttpServletRequestSpanExtractor() {
return new CustomHttpServletRequestSpanExtractor();
}
Spring Cloud Sleuth does not add trace/span related headers to the Http Response for security reasons. If you need the headers then a custom SpanInjector
that injects the headers into the Http Response and a Servlet filter which makes use of this can be added the following way:
static class CustomHttpServletResponseSpanInjector
implements SpanInjector<HttpServletResponse> {
@Override
public void inject(Span span, HttpServletResponse carrier) {
carrier.addHeader(Span.TRACE_ID_NAME, span.traceIdString());
carrier.addHeader(Span.SPAN_ID_NAME, Span.idToHex(span.getSpanId()));
}
}
static class HttpResponseInjectingTraceFilter extends GenericFilterBean {
private final Tracer tracer;
private final SpanInjector<HttpServletResponse> spanInjector;
public HttpResponseInjectingTraceFilter(Tracer tracer, SpanInjector<HttpServletResponse> spanInjector) {
this.tracer = tracer;
this.spanInjector = spanInjector;
}
@Override
public void doFilter(ServletRequest request, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) servletResponse;
Span currentSpan = this.tracer.getCurrentSpan();
this.spanInjector.inject(currentSpan, response);
filterChain.doFilter(request, response);
}
}
And you could register them like this:
@Bean
SpanInjector<HttpServletResponse> customHttpServletResponseSpanInjector() {
return new CustomHttpServletResponseSpanInjector();
}
@Bean
HttpResponseInjectingTraceFilter responseInjectingTraceFilter(Tracer tracer) {
return new HttpResponseInjectingTraceFilter(tracer, customHttpServletResponseSpanInjector());
}
Sometimes you want to create a manual Span that will wrap a call to an external service which is not instrumented.
What you can do is to create a span with the peer.service tag that will contain a value of the service that you want to call.
Below you can see an example of a call to Redis that is wrapped in such a span.
org.springframework.cloud.sleuth.Span newSpan = tracer.createSpan("redis");
try {
newSpan.tag("redis.op", "get");
newSpan.tag("lc", "redis");
newSpan.logEvent(org.springframework.cloud.sleuth.Span.CLIENT_SEND);
// call redis service e.g
// return (SomeObj) redisTemplate.opsForHash().get("MYHASH", someObjKey);
} finally {
newSpan.tag("peer.service", "redisService");
newSpan.tag("peer.ipv4", "1.2.3.4");
newSpan.tag("peer.port", "1234");
newSpan.logEvent(org.springframework.cloud.sleuth.Span.CLIENT_RECV);
tracer.close(newSpan);
}
|
Important
|
Remember not to add both peer.service tag and the SA tag! You have to add only peer.service.
|
By default Sleuth assumes that when you send a span to Zipkin, you want the span’s service name
to be equal to spring.application.name value. That’s not always the case though. There
are situations in which you want to explicitly provide a different service name for all spans coming
from your application. To achieve that it’s enough to just pass the following property
to your application to override that value (example for foo service name):
spring.zipkin.service.name: foo
You can accumulate and send span data over
Spring Cloud Stream by
including the spring-cloud-sleuth-stream jar as a dependency, and
adding a Channel Binder implementation
(e.g. spring-cloud-starter-stream-rabbit for RabbitMQ or
spring-cloud-starter-stream-kafka for Kafka). This will
automatically turn your app into a producer of messages with payload
type Spans.
There is a special convenience annotation for setting up a message consumer
for the Span data and pushing it into a Zipkin SpanStore. This application
@SpringBootApplication
@EnableZipkinStreamServer
public class Consumer {
public static void main(String[] args) {
SpringApplication.run(Consumer.class, args);
}
}
will listen for the Span data on whatever transport you provide via a
Spring Cloud Stream Binder (e.g. include
spring-cloud-starter-stream-rabbit for RabbitMQ, and similar
starters exist for Redis and Kafka). If you add the following UI dependency
<groupId>io.zipkin.java</groupId>
<artifactId>zipkin-autoconfigure-ui</artifactId>
Then you’ll have your app a Zipkin server, which hosts the UI and api on port 9411.
The default SpanStore is in-memory (good for demos and getting
started quickly). For a more robust solution you can add MySQL and
spring-boot-starter-jdbc to your classpath and enable the JDBC
SpanStore via configuration, e.g.:
spring:
rabbitmq:
host: ${RABBIT_HOST:localhost}
datasource:
schema: classpath:/mysql.sql
url: jdbc:mysql://${MYSQL_HOST:localhost}/test
username: root
password: root
# Switch this on to create the schema on startup:
initialize: true
continueOnError: true
sleuth:
enabled: false
zipkin:
storage:
type: mysql
|
Note
|
The @EnableZipkinStreamServer is also annotated with
@EnableZipkinServer so the process will also expose the standard
Zipkin server endpoints for collecting spans over HTTP, and for
querying in the Zipkin Web UI.
|
A custom consumer can also easily be implemented using
spring-cloud-sleuth-stream and binding to the SleuthSink. Example:
@EnableBinding(SleuthSink.class)
@SpringBootApplication(exclude = SleuthStreamAutoConfiguration.class)
@MessageEndpoint
public class Consumer {
@ServiceActivator(inputChannel = SleuthSink.INPUT)
public void sink(Spans input) throws Exception {
// ... process spans
}
}
|
Note
|
the sample consumer application above explicitly excludes
SleuthStreamAutoConfiguration so it doesn’t send messages to itself,
but this is optional (you might actually want to trace requests into
the consumer app).
|
Currently Spring Cloud Sleuth registers very simple metrics related to spans. It’s using the Spring Boot’s metrics support to calculate the number of accepted and dropped spans. Each time a span gets sent to Zipkin the number of accepted spans will increase. If there’s an error then the number of dropped spans will get increased.
If you’re wrapping your logic in Runnable or Callable it’s enough to wrap those classes in their Sleuth representative.
Example for Runnable:
Runnable runnable = new Runnable() {
@Override
public void run() {
// do some work
}
@Override
public String toString() {
return "spanNameFromToStringMethod";
}
};
// Manual `TraceRunnable` creation with explicit "calculateTax" Span name
Runnable traceRunnable = new TraceRunnable(tracer, spanNamer, runnable, "calculateTax");
// Wrapping `Runnable` with `Tracer`. The Span name will be taken either from the
// `@SpanName` annotation or from `toString` method
Runnable traceRunnableFromTracer = tracer.wrap(runnable);
Example for Callable:
Callable<String> callable = new Callable<String>() {
@Override
public String call() throws Exception {
return someLogic();
}
@Override
public String toString() {
return "spanNameFromToStringMethod";
}
};
// Manual `TraceCallable` creation with explicit "calculateTax" Span name
Callable<String> traceCallable = new TraceCallable<>(tracer, spanNamer, callable, "calculateTax");
// Wrapping `Callable` with `Tracer`. The Span name will be taken either from the
// `@SpanName` annotation or from `toString` method
Callable<String> traceCallableFromTracer = tracer.wrap(callable);
That way you will ensure that a new Span is created and closed for each execution.
We’re registering a custom HystrixConcurrencyStrategy
that wraps all Callable instances into their Sleuth representative -
the TraceCallable. The strategy either starts or continues a span depending on the fact whether tracing was already going
on before the Hystrix command was called. To disable the custom Hystrix Concurrency Strategy set the spring.sleuth.hystrix.strategy.enabled to false.
Assuming that you have the following HystrixCommand:
HystrixCommand<String> hystrixCommand = new HystrixCommand<String>(setter) {
@Override
protected String run() throws Exception {
return someLogic();
}
};
In order to pass the tracing information you have to wrap the same logic in the Sleuth version of the HystrixCommand which is the
TraceCommand:
TraceCommand<String> traceCommand = new TraceCommand<String>(tracer, traceKeys, setter) {
@Override
public String doRun() throws Exception {
return someLogic();
}
};
We’re registering a custom RxJavaSchedulersHook
that wraps all Action0 instances into their Sleuth representative -
the TraceAction. The hook either starts or continues a span depending on the fact whether tracing was already going
on before the Action was scheduled. To disable the custom RxJavaSchedulersHook set the spring.sleuth.rxjava.schedulers.hook.enabled to false.
You can define a list of regular expressions for thread names, for which you don’t want a Span to be created. Just provide a comma separated list
of regular expressions in the spring.sleuth.rxjava.schedulers.ignoredthreads property.
Features from this section can be disabled by providing the spring.sleuth.web.enabled property with value equal to false.
Via the TraceFilter all sampled incoming requests result in creation of a Span. That Span’s name is http: + the path to which
the request was sent. E.g. if the request was sent to /foo/bar then the name will be http:/foo/bar. You can configure which URIs you would
like to skip via the spring.sleuth.web.skipPattern property. If you have ManagementServerProperties on classpath then
its value of contextPath gets appended to the provided skip pattern.
Since we want the span names to be precise we’re using a TraceHandlerInterceptor that either wraps an
existing HandlerInterceptor or is added directly to the list of existing HandlerInterceptors. The
TraceHandlerInterceptor adds a special request attribute to the given HttpServletRequest. If the
the TraceFilter doesn’t see this attribute set it will create a "fallback" span which is an additional
span created on the server side so that the trace is presented properly in the UI. Seeing that most likely
signifies that there is a missing instrumentation. In that case please file an issue in Spring Cloud Sleuth.
If your controller returns a Callable or a WebAsyncTask Spring Cloud Sleuth will continue the existing span instead of creating a new one.
We’re injecting a RestTemplate interceptor that ensures that all the tracing information is passed to the requests. Each time a
call is made a new Span is created. It gets closed upon receiving the response. In order to block the synchronous RestTemplate features
just set spring.sleuth.web.client.enabled to false.
|
Important
|
You have to register RestTemplate as a bean so that the interceptors will get injected.
If you create a RestTemplate instance with a new keyword then the instrumentation WILL NOT work.
|
|
Important
|
A traced version of an AsyncRestTemplate bean is registered for you out of the box. If you
have your own bean you have to wrap it in a TraceAsyncRestTemplate representation. The best solution
is to only customize the ClientHttpRequestFactory and / or AsyncClientHttpRequestFactory.
If you have your own AsyncRestTemplate and you don’t wrap it your calls WILL NOT GET TRACED.
|
Custom instrumentation is set to create and close Spans upon sending and receiving requests. You can customize the ClientHttpRequestFactory
and the AsyncClientHttpRequestFactory by registering your beans. Remember to use tracing compatible implementations (e.g. don’t forget to
wrap ThreadPoolTaskScheduler in a TraceAsyncListenableTaskExecutor). Example of custom request factories:
@EnableAutoConfiguration
@Configuration
public static class TestConfiguration {
@Bean
ClientHttpRequestFactory mySyncClientFactory() {
return new MySyncClientHttpRequestFactory();
}
@Bean
AsyncClientHttpRequestFactory myAsyncClientFactory() {
return new MyAsyncClientHttpRequestFactory();
}
}
To block the AsyncRestTemplate features set spring.sleuth.web.async.client.enabled to false.
To disable creation of the default TraceAsyncClientHttpRequestFactoryWrapper set spring.sleuth.web.async.client.factory.enabled
to false. If you don’t want to create AsyncRestClient at all set spring.sleuth.web.async.client.template.enabled to false.
By default Spring Cloud Sleuth provides integration with feign via the TraceFeignClientAutoConfiguration. You can disable it entirely
by setting spring.sleuth.feign.enabled to false. If you do so then no Feign related instrumentation will take place.
Part of Feign instrumentation is done via a FeignBeanPostProcessor. You can disable it by providing the spring.sleuth.feign.processor.enabled equal to false.
If you set it like this then Spring Cloud Sleuth will not instrument any of your custom Feign components. All the default instrumentation
however will be still there.
In Spring Cloud Sleuth we’re instrumenting async related components so that the tracing information is passed between threads.
You can disable this behaviour by setting the value of spring.sleuth.async.enabled to false.
If you annotate your method with @Async then we’ll automatically create a new Span with the following characteristics:
the Span name will be the annotated method name
the Span will be tagged with that method’s class name and the method name too
In Spring Cloud Sleuth we’re instrumenting scheduled method execution so that the tracing information is passed between threads. You can disable this behaviour
by setting the value of spring.sleuth.scheduled.enabled to false.
If you annotate your method with @Scheduled then we’ll automatically create a new Span with the following characteristics:
the Span name will be the annotated method name
the Span will be tagged with that method’s class name and the method name too
If you want to skip Span creation for some @Scheduled annotated classes you can set the
spring.sleuth.scheduled.skipPattern with a regular expression that will match the fully qualified name of the
@Scheduled annotated class.
|
Tip
|
If you are using spring-cloud-sleuth-stream and spring-cloud-netflix-hystrix-stream together, Span will be created for each Hystrix metrics and sent to Zipkin. This may be annoying. You can prevent this by setting spring.sleuth.scheduled.skipPattern=org.springframework.cloud.netflix.hystrix.stream.HystrixStreamTask
|
We’re providing LazyTraceExecutor, TraceableExecutorService and TraceableScheduledExecutorService. Those implementations
are creating Spans each time a new task is submitted, invoked or scheduled.
Here you can see an example of how to pass tracing information with TraceableExecutorService when working with CompletableFuture:
CompletableFuture<Long> completableFuture = CompletableFuture.supplyAsync(() -> {
// perform some logic
return 1_000_000L;
}, new TraceableExecutorService(executorService,
// 'calculateTax' explicitly names the span - this param is optional
tracer, traceKeys, spanNamer, "calculateTax"));
Spring Cloud Sleuth integrates with Spring Integration. It creates spans for publish and
subscribe events. To disable Spring Integration instrumentation, set spring.sleuth.integration.enabled to false.
Spring Cloud Sleuth up till version 1.0.4 is sending invalid tracing headers when using messaging. Those headers are actually
the same as the ones sent in HTTP (they contain a -) in its name. For the sake of
backwards compatibility in 1.0.4 we’ve started sending both valid and invalid headers. Please upgrade to 1.0.4 because
in Spring Cloud Sleuth 1.1 we will remove the support for the deprecated headers.
Since 1.0.4 you can provide the spring.sleuth.integration.patterns pattern to explicitly
provide the names of channels that you want to include for tracing. By default all channels
are included.
We’re registering Zuul filters to propagate the tracing information (the request header is enriched with tracing data).
To disable Zuul support set the spring.sleuth.zuul.enabled property to false.
You can find the running examples deployed in the Pivotal Web Services. Check them out in the following links:
Please see the installation documentation for instructions on how to install Consul.
A Consul Agent client must be available to all Spring Cloud Consul applications. By default, the Agent client is expected to be at localhost:8500. See the Agent documentation for specifics on how to start an Agent client and how to connect to a cluster of Consul Agent Servers. For development, after you have installed consul, you may start a Consul Agent using the following command:
./src/main/bash/local_run_consul.sh
This will start an agent in server mode on port 8500, with the ui available at http://localhost:8500
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. Consul provides Service Discovery services via an HTTP API and DNS. Spring Cloud Consul leverages the HTTP API for service registration and discovery. This does not prevent non-Spring Cloud applications from leveraging the DNS interface. Consul Agents servers are run in a cluster that communicates via a gossip protocol and uses the Raft consensus protocol.
When a client registers with Consul, it provides meta-data about itself such as host and port, id, name and tags. An HTTP Check is created by default that Consul hits the /health endpoint every 10 seconds. If the health check fails, the service instance is marked as critical.
Example Consul client:
@SpringBootApplication
@EnableDiscoveryClient
@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). If the Consul client is located somewhere other than localhost:8500, the configuration is required to locate the client. Example:
spring:
cloud:
consul:
host: localhost
port: 8500
|
Caution
|
If you use Spring Cloud Consul Config, the above values will need to be placed in bootstrap.yml instead of application.yml.
|
The default service name, instance id and port, taken from the Environment, are ${spring.application.name}, the Spring Context ID and ${server.port} respectively.
@EnableDiscoveryClient make the app into both a Consul "service" (i.e. it registers itself) and a "client" (i.e. it can query Consul to locate other services).
The health check for a Consul instance defaults to "/health", which is the default locations of a useful endpoint in a Spring Boot Actuator application. You need to change these, even for an Actuator application if you use a non-default context path or servlet path (e.g. server.servletPath=/foo) or management endpoint path (e.g. management.contextPath=/admin). The interval that Consul uses to check the health endpoint may also be configured. "10s" and "1m" represent 10 seconds and 1 minute respectively. Example:
spring:
cloud:
consul:
discovery:
healthCheckPath: ${management.contextPath}/health
healthCheckInterval: 15s
Consul does not yet support metadata on services. Spring Cloud’s ServiceInstance has a Map<String, String> metadata field. Spring Cloud Consul uses Consul tags to approximate metadata until Consul officially supports metadata. Tags with the form key=value will be split and used as a Map key and value respectively. Tags without the equal = sign, will be used as both the key and value.
spring:
cloud:
consul:
discovery:
tags: foo=bar, baz
The above configuration will result in a map with foo→bar and baz→baz.
By default a consul instance is registered with an ID that is equal to its Spring Application Context ID. By default, the Spring Application Context ID is ${spring.application.name}:comma,separated,profiles:${server.port}. For most cases, this will allow multiple instances of one service to run on one machine. If further uniqueness is required, Using Spring Cloud you can override this by providing a unique identifier in spring.cloud.consul.discovery.instanceId. For example:
spring:
cloud:
consul:
discovery:
instanceId: ${spring.application.name}:${spring.application.instance_id:${random.value}}
With this metadata, and multiple service instances deployed on localhost, the random value will kick in there to make the instance unique. In Cloudfoundry the spring.application.instance_id will be populated automatically in a Spring Boot Actuator application, so the random value will not be needed.
Spring Cloud has support for Feign (a REST client builder) and also Spring RestTemplate using the logical service names instead of physical URLs.
You can also use the org.springframework.cloud.client.discovery.DiscoveryClient which provides a simple API for discovery clients that is not specific to Netflix, e.g.
@Autowired
private DiscoveryClient discoveryClient;
public String serviceUrl() {
List<ServiceInstance> list = discoveryClient.getInstances("STORES");
if (list != null && list.size() > 0 ) {
return list.get(0).getUri();
}
return null;
}
Consul provides a Key/Value Store for storing configuration and other metadata. Spring Cloud Consul Config is an alternative to the Config Server and Client. Configuration is loaded into the Spring Environment during the special "bootstrap" phase. Configuration is stored in the /config folder by default. Multiple PropertySource instances are created based on the application’s name and the active profiles that mimicks the Spring Cloud Config order of resolving properties. For example, an application with the name "testApp" and with the "dev" profile will have the following property sources created:
config/testApp,dev/ config/testApp/ config/application,dev/ config/application/
The most specific property source is at the top, with the least specific at the bottom. Properties is the config/application folder are applicable to all applications using consul for configuration. Properties in the config/testApp folder are only available to the instances of the service named "testApp".
Configuration is currently read on startup of the application. Sending a HTTP POST to /refresh will cause the configuration to be reloaded. Watching the key value store (which Consul supports) is not currently possible, but will be a future addition to this project.
Including a dependency on org.springframework.cloud:spring-cloud-consul-config will enable auto-configuration that will setup Spring Cloud Consul Config.
Consul Config may be customized using the following properties:
spring:
cloud:
consul:
config:
enabled: true
prefix: configuration
defaultContext: apps
profileSeparator: '::'
enabled setting this value to "false" disables Consul Config
prefix sets the base folder for configuration values
defaultContext sets the folder name used by all applications
profileSeparator sets the value of the separator used to separate the profile name in property sources with profiles
It may be more convenient to store a blob of properties in YAML or Properties format as opposed to individual key/value pairs. Set the spring.cloud.consul.config.format property to YAML or PROPERTIES. For example to use YAML:
spring:
cloud:
consul:
config:
format: YAML
YAML must be set in the appropriate data key in consul. Using the defaults above the keys would look like:
config/testApp,dev/data config/testApp/data config/application,dev/data config/application/data
You could store a YAML document in any of the keys listed above.
You can change the data key using spring.cloud.consul.config.data-key.
git2consul is a Consul community project that loads files from a git repository to individual keys into Consul. By default the names of the keys are names of the files. YAML and Properties files are supported with file extensions of .yml and .properties respectively. Set the spring.cloud.consul.config.format property to FILES. For example:
spring:
cloud:
consul:
config:
format: FILES
Given the following keys in /config, the development profile and an application name of foo:
.gitignore application.yml bar.properties foo-development.properties foo-production.yml foo.properties master.ref
the following property sources would be created:
config/foo-development.properties config/foo.properties config/application.yml
The value of each key needs to be a properly formatted YAML or Properties file.
It may be convenient in certain circumstances (like local development or certain test scenarios) to not fail if consul isn’t available for configuration. Setting spring.cloud.consul.config.failFast=false in bootstrap.yml will cause the configuration module to log a warning rather than throw an exception. This will allow the application to continue startup normally.
If you expect that the consul agent may occasionally be unavailable when
your app starts, you can ask it to keep trying after a failure. You need to add
spring-retry and spring-boot-starter-aop to your classpath. The default
behaviour is to retry 6 times with an initial backoff interval of 1000ms and an
exponential multiplier of 1.1 for subsequent backoffs. You can configure these
properties (and others) using spring.cloud.consul.retry.* configuration properties.
This works with both Spring Cloud Consul Config and Discovery registration.
|
Tip
|
To take full control of the retry add a @Bean of type
RetryOperationsInterceptor with id "consulRetryInterceptor". Spring
Retry has a RetryInterceptorBuilder that makes it easy to create one.
|
Coming in a later release.
Applications can use the Hystrix Circuit Breaker provided by the Spring Cloud Netflix project by including this starter in the projects pom.xml: spring-cloud-starter-hystrix. Hystrix doesn’t depend on the Netflix Discovery Client. The @EnableHystrix annotation should be placed on a configuration class (usually the main class). Then methods can be annotated with @HystrixCommand to be protected by a circuit breaker. See the documentation for more details.
Turbine (provided by the Spring Cloud Netflix project), aggregates multiple instances Hystrix metrics streams, so the dashboard can display an aggregate view. Turbine uses the DiscoveryClient interface to lookup relevant instances. To use Turbine with Spring Cloud Consul, configure the Turbine application in a manner similar to the following examples:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-netflix-turbine</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-consul-discovery</artifactId>
</dependency>
Notice that the Turbine dependency is not a starter. The turbine starter includes support for Netflix Eureka.
spring.application.name: turbine
applications: consulhystrixclient
turbine:
aggregator:
clusterConfig: ${applications}
appConfig: ${applications}
The clusterConfig and appConfig sections must match, so it’s useful to put the comma-separated list of service ID’s into a separate configuration property.
@EnableTurbine
@EnableDiscoveryClient
@SpringBootApplication
public class Turbine {
public static void main(String[] args) {
SpringApplication.run(DemoturbinecommonsApplication.class, args);
}
}
Please see the installation documentation for instructions on how to install Zookeeper.
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. Curator(A java library for Zookeeper) provides Service Discovery services via Service Discovery Extension. Spring Cloud Zookeeper leverages this extension for service registration and discovery.
Including a dependency on org.springframework.cloud:spring-cloud-starter-zookeeper-discovery will enable auto-configuration that will setup Spring Cloud Zookeeper Discovery.
When a client registers with Zookeeper, it provides meta-data about itself such as host and port, id and name.
Example Zookeeper client:
@SpringBootApplication
@EnableDiscoveryClient
@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). If Zookeeper is located somewhere other than localhost:2181, the configuration is required to locate the server. Example:
spring:
cloud:
zookeeper:
connect-string: localhost:2181
|
Caution
|
If you use Spring Cloud Zookeeper Config, the above values will need to be placed in bootstrap.yml instead of application.yml.
|
The default service name, instance id and port, taken from the Environment, are ${spring.application.name}, the Spring Context ID and ${server.port} respectively.
@EnableDiscoveryClient makes the app into both a Zookeeper "service" (i.e. it registers itself) and a "client" (i.e. it can query Zookeeper to locate other services).
Spring Cloud has support for Feign (a REST client builder) and also Spring RestTemplate using the logical service names instead of physical URLs.
You can also use the org.springframework.cloud.client.discovery.DiscoveryClient which provides a simple API for discovery clients that is not specific to Netflix, e.g.
@Autowired
private DiscoveryClient discoveryClient;
public String serviceUrl() {
List<ServiceInstance> list = discoveryClient.getInstances("STORES");
if (list != null && list.size() > 0 ) {
return list.get(0).getUri().toString();
}
return null;
}
Spring Cloud Zookeeper gives you a possibility to provide dependencies of your application as properties. As dependencies you can understand other applications that are registered
in Zookeeper and which you would like to call via Feign (a REST client builder)
and also Spring RestTemplate.
You can also benefit from the Zookeeper Dependency Watchers functionality that lets you control and monitor what is the state of your dependencies and decide what to do with that.
Including a dependency on org.springframework.cloud:spring-cloud-starter-zookeeper-discovery will enable auto-configuration that will setup Spring Cloud Zookeeper Dependencies.
If you have to have the spring.cloud.zookeeper.dependencies section properly set up - check the subsequent section for more details then the feature is active
You can have the dependencies turned off even if you’ve provided the dependencies in your properties. Just set the property spring.cloud.zookeeper.dependency.enabled to false (defaults to true).
Let’s take a closer look at an example of dependencies representation:
spring.application.name: yourServiceName
spring.cloud.zookeeper:
dependencies:
newsletter:
path: /path/where/newsletter/has/registered/in/zookeeper
loadBalancerType: ROUND_ROBIN
contentTypeTemplate: application/vnd.newsletter.$version+json
version: v1
headers:
header1:
- value1
header2:
- value2
required: false
stubs: org.springframework:foo:stubs
mailing:
path: /path/where/mailing/has/registered/in/zookeeper
loadBalancerType: ROUND_ROBIN
contentTypeTemplate: application/vnd.mailing.$version+json
version: v1
required: true
Let’s now go through each part of the dependency one by one. The root property name is spring.cloud.zookeeper.dependencies.
Below the root property you have to represent each dependency has by an alias due to the constraints of Ribbon (the application id has to be placed in the URL
thus you can’t pass any complex path like /foo/bar/name). The alias will be the name that you will use instead of serviceId for DiscoveryClient, Feign or RestTemplate.
In the aforementioned examples the aliases are newsletter and mailing. Example of Feign usage with newsletter would be:
@FeignClient("newsletter")
public interface NewsletterService {
@RequestMapping(method = RequestMethod.GET, value = "/newsletter")
String getNewsletters();
}
Represented by path yaml property.
Path is the path under which the dependency is registered under Zookeeper. Like presented before Ribbon operates on URLs thus this path is not compliant with its requirement. That is why Spring Cloud Zookeeper maps the alias to the proper path.
Represented by loadBalancerType yaml property.
If you know what kind of load balancing strategy has to be applied when calling this particular dependency then you can provide it in the yaml file and it will be automatically applied. You can choose one of the following load balancing strategies
STICKY - once chosen the instance will always be called
RANDOM - picks an instance randomly
ROUND_ROBIN - iterates over instances over and over again
Represented by contentTypeTemplate and version yaml property.
If you version your api via the Content-Type header then you don’t want to add this header to each of your requests. Also if you want to call a new version of the API you don’t want to
roam around your code to bump up the API version. That’s why you can provide a contentTypeTemplate with a special $version placeholder. That placeholder will be filled by the value of the
version yaml property. Let’s take a look at an example.
Having the following contentTypeTemplate:
application/vnd.newsletter.$version+json
and the following version:
v1
Will result in setting up of a Content-Type header for each request:
application/vnd.newsletter.v1+json
Represented by headers map in yaml
Sometimes each call to a dependency requires setting up of some default headers. In order not to do that in code you can set them up in the yaml file.
Having the following headers section:
headers:
Accept:
- text/html
- application/xhtml+xml
Cache-Control:
- no-cache
Results in adding the Accept and Cache-Control headers with appropriate list of values in your HTTP request.
Represented by required property in yaml
If one of your dependencies is required to be up and running when your application is booting then it’s enough to set up the required: true property in the yaml file.
If your application can’t localize the required dependency during boot time it will throw an exception and the Spring Context will fail to set up. In other words your application won’t be able to start if the required dependency is not registered in Zookeeper.
You can read more about Spring Cloud Zookeeper Presence Checker in the following sections.
You can provide a colon separated path to the JAR containing stubs of the dependency. Example
stubs: org.springframework:foo:stubs
means that for a particular dependencies can be found under:
groupId: org.springframework
artifactId: foo
classifier: stubs - this is the default value
This is actually equal to
stubs: org.springframework:foo
since stubs is the default classifier.
There is a bunch of properties that you can set to enable / disable parts of Zookeeper Dependencies functionalities.
spring.cloud.zookeeper.dependencies - if you don’t set this property you won’t benefit from Zookeeper Dependencies
spring.cloud.zookeeper.dependency.ribbon.enabled (enabled by default) - Ribbon requires explicit global configuration or a particular one for a dependency. By turning on this property
runtime load balancing strategy resolution is possible and you can profit from the loadBalancerType section of the Zookeeper Dependencies. The configuration that needs this property
has an implementation of LoadBalancerClient that delegates to the ILoadBalancer presented in the next bullet
spring.cloud.zookeeper.dependency.ribbon.loadbalancer (enabled by default) - thanks to this property the custom ILoadBalancer knows that the part of the URI passed to Ribbon might
actually be the alias that has to be resolved to a proper path in Zookeeper. Without this property you won’t be able to register applications under nested paths.
spring.cloud.zookeeper.dependency.headers.enabled (enabled by default) - this property registers such a RibbonClient that automatically will append appropriate headers and content
types with version as presented in the Dependency configuration. Without this setting of those two parameters will not be operational.
spring.cloud.zookeeper.dependency.resttemplate.enabled (enabled by default) - when enabled will modify the request headers of @LoadBalanced annotated RestTemplate so that it passes
headers and content type with version set in Dependency configuration. Wihtout this setting of those two parameters will not be operational.
The Dependency Watcher mechanism allows you to register listeners to your dependencies. The functionality is in fact an implementation of the Observator pattern. When a dependency changes
its state (UP or DOWN) then some custom logic can be applied.
Spring Cloud Zookeeper Dependencies functionality needs to be enabled to profit from Dependency Watcher mechanism.
In order to register a listener you have to implement an interface org.springframework.cloud.zookeeper.discovery.watcher.DependencyWatcherListener and register it as a bean.
The interface gives you one method:
void stateChanged(String dependencyName, DependencyState newState);
If you want to register a listener for a particular dependency then the dependencyName would be the discriminator for your concrete implementation. newState will provide you with information
whether your dependency has changed to CONNECTED or DISCONNECTED.
Bound with Dependency Watcher is the functionality called Presence Checker. It allows you to provide custom behaviour upon booting of your application to react accordingly to the state of your dependencies.
The default implementation of the abstract org.springframework.cloud.zookeeper.discovery.watcher.presence.DependencyPresenceOnStartupVerifier class is the
org.springframework.cloud.zookeeper.discovery.watcher.presence.DefaultDependencyPresenceOnStartupVerifier which works in the following way.
If the dependency is marked us required and it’s not in Zookeeper then upon booting your application will throw an exception and shutdown
If dependency is not required the org.springframework.cloud.zookeeper.discovery.watcher.presence.LogMissingDependencyChecker will log that application is missing at WARN level
The functionality can be overriden since the DefaultDependencyPresenceOnStartupVerifier is registered only when there is no bean of DependencyPresenceOnStartupVerifier.
Zookeeper provides a hierarchical namespace that allows clients to store arbitrary data, such as configuration data. Spring Cloud Zookeeper Config is an alternative to the Config Server and Client. Configuration is loaded into the Spring Environment during the special "bootstrap" phase. Configuration is stored in the /config namespace by default. Multiple PropertySource instances are created based on the application’s name and the active profiles that mimicks the Spring Cloud Config order of resolving properties. For example, an application with the name "testApp" and with the "dev" profile will have the following property sources created:
config/testApp,dev config/testApp config/application,dev config/application
The most specific property source is at the top, with the least specific at the bottom. Properties is the config/application namespace are applicable to all applications using zookeeper for configuration. Properties in the config/testApp namespace are only available to the instances of the service named "testApp".
Configuration is currently read on startup of the application. Sending a HTTP POST to /refresh will cause the configuration to be reloaded. Watching the configuration namespace (which Zookeeper supports) is not currently implemented, but will be a future addition to this project.
Including a dependency on org.springframework.cloud:spring-cloud-starter-zookeeper-config will enable auto-configuration that will setup Spring Cloud Zookeeper Config.
Zookeeper Config may be customized using the following properties:
spring:
cloud:
zookeeper:
config:
enabled: true
root: configuration
defaultContext: apps
profileSeparator: '::'
enabled setting this value to "false" disables Zookeeper Config
root sets the base namespace for configuration values
defaultContext sets the name used by all applications
profileSeparator sets the value of the separator used to separate the profile name in property sources with profiles
@EnableEurekaServer). You can also easily do
things like encryption and decryption to support Spring Cloud Config
clients with secret configuration values. With the Launcher CLI you
can launch services like Eureka, Zipkin, Config Server
conveniently all at once from the command line (very useful at
development time).
To install, make sure you have Spring Boot CLI (1.4.1 or better):
$ spring version Spring CLI v1.4.1.RELEASE
E.g. for SDKMan users
$ sdk install springboot 1.4.1.RELEASE
$ sdk use springboot 1.4.1.RELEASE
and install the Spring Cloud plugin
$ mvn install
$ spring install org.springframework.cloud:spring-cloud-cli:1.2.3.BUILD-SNAPSHOT
|
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 Launcher CLI can be used to run common services like Eureka,
Config Server etc. from the command line. To list the available
services you can do spring cloud --list, and to launch a default set
of services just spring cloud. To choose the services to deploy,
just list them on the command line, e.g.
$ spring cloud eureka configserver h2 kafka zipkin
Summary of supported deployables:
| Service | Name | Address | Description |
|---|---|---|---|
eureka |
Eureka Server |
Eureka server for service registration and discovery. All the other services show up in its catalog by default. |
|
configserver |
Config Server |
Spring Cloud Config Server running in the "native" profile and serving configuration from the local directory ./launcher |
|
h2 |
H2 Database |
http://localhost:9095 (console), jdbc:h2:tcp://localhost:9096/{data} |
Relation database service. Use a file path for |
kafka |
Kafka Broker |
http://localhost:9091 (actuator endpoints), localhost:9092 |
|
hystrixdashboard |
Hystrix Dashboard |
Any Spring Cloud app that declares Hystrix circuit breakers publishes metrics on |
|
dataflow |
Dataflow Server |
Spring Cloud Dataflow server with UI at /admin-ui. Connect the Dataflow shell to target at root path. |
|
zipkin |
Zipkin Server |
Zipkin Server with UI for visualizing traces. Stores span data in memory and accepts them via HTTP POST of JSON data. |
Each of these apps can be configured using a local YAML file with the same name (in the current
working directory or a subdirectory called "config" or in ~/.spring-cloud). E.g. in configserver.yml you might want to
do something like this to locate a local git repository for the backend:
spring:
profiles:
active: git
cloud:
config:
server:
git:
uri: file://${user.home}/dev/demo/config-repo
Additional applications can be added to ./config/cloud.yml (not
./config.yml because that would replace the defaults), e.g. with
spring:
cloud:
launcher:
deployables:
source:
coordinates: maven://com.example:source:0.0.1-SNAPSHOT
port: 7000
sink:
coordinates: maven://com.example:sink:0.0.1-SNAPSHOT
port: 7001
when you list the apps:
$ spring cloud --list
source sink configserver dataflow eureka h2 hystrixdashboard kafka zipkin
(notice the additional apps at the start of the list).
Spring Cloud CLI has support for most of the Spring Cloud declarative
features, such as the @Enable* class of annotations. For example,
here is a fully functional Eureka server
@EnableEurekaServer
class Eureka {}
which you can run from the command line like this
$ spring run app.groovy
To include additional dependencies, often it suffices just to add the
appropriate feature-enabling annotation, e.g. @EnableConfigServer,
@EnableOAuth2Sso or @EnableEurekaClient. To manually include a
dependency you can use a @Grab with the special "Spring Boot" short
style artifact co-ordinates, i.e. with just the artifact ID (no need
for group or version information), e.g. to set up a client app to
listen on AMQP for management events from the Spring CLoud Bus:
@Grab('spring-cloud-starter-bus-amqp')
@RestController
class Service {
@RequestMapping('/')
def home() { [message: 'Hello'] }
}
The Spring Cloud CLI comes with an "encrypt" and a "decrypt" command. Both accept arguments in the same form with a key specified as a mandatory "--key", 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+...
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:
spring:
oauth2:
client:
clientId: bd1c0a783ccdd1c9b9e4
clientSecret: 1a9030fbca47a5b2c28e92f19050bb77824b5ad1
accessTokenUri: https://github.com/login/oauth/access_token
userAuthorizationUri: https://github.com/login/oauth/authorize
clientAuthenticationScheme: 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.
To limit the scope that the client asks for when it obtains an access token
you can set spring.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.
|
Note
|
The examples above are all Groovy scripts. If you want to write the same code in Java (or Groovy) you need to add Spring Security OAuth2 to the classpath (e.g. see the sample here). |
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
@EnableResourceServer
class Application {
@RequestMapping('/')
def home() {
[message: 'Hello World']
}
}
and
spring:
oauth2:
resource:
userInfoUri: https://api.github.com/user
preferTokenInfo: false
|
Note
|
All of the OAuth2 SSO and resource server features moved to Spring Boot in version 1.3. You can find documentation in the Spring Boot user guide. |
A Token Relay is where an OAuth2 consumer acts as a Client and forwards the incoming token to outgoing resource requests. The consumer can be a pure Client (like an SSO application) or a Resource Server.
If your app is a user facing OAuth2 client (i.e. has declared
@EnableOAuth2Sso or @EnableOAuth2Client) then it has an
OAuth2ClientContext in request scope from Spring Boot. You can
create your own OAuth2RestTemplate from this context and an
autowired OAuth2ProtectedResourceDetails, and then the context will
always forward the access token downstream, also refreshing the access
token automatically if it expires. (These are features of Spring
Security and Spring Boot.)
|
Note
|
Spring Boot (1.4.1) does not create an
OAuth2ProtectedResourceDetails automatically if you are using
client_credentials tokens. In that case you need to create your own
ClientCredentialsResourceDetails and configure it with
@ConfigurationProperties("security.oauth2.client").
|
If your app also 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 {
}
and it will (in addition to logging the user in and grabbing a token)
pass the authentication token downstream to the /proxy/*
services. If those services are implemented with
@EnableResourceServer 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 in turn triggers 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.
If your app has @EnableResourceServer you might want to relay the
incoming token downstream to other services. If you use a
RestTemplate to contact the downstream services then this is just a
matter of how to create the template with the right context.
If your service uses UserInfoTokenServices to authenticate incoming
tokens (i.e. it is using the security.oauth2.user-info-uri
configuration), then you can simply create an OAuth2RestTemplate
using an autowired OAuth2ClientContext (it will be populated by the
authentication process before it hits the backend code). Equivalently
(with Spring Boot 1.4), you could inject a
UserInfoRestTemplateFactory and grab its OAuth2RestTemplate in
your configuration. For example:
@Bean
public OAuth2RestTemplate restTemplate(UserInfoRestTemplateFactory factory) {
return factory.getUserInfoRestTemplate();
}
This rest template will then have the same OAuth2ClientContext
(request-scoped) that is used by the authentication filter, so you can
use it to send requests with the same access token.
If your app is not using UserInfoTokenServices but is still a client
(i.e. it declares @EnableOAuth2Client or @EnableOAuth2Sso), then
with Spring Security Cloud any OAuth2RestOperations that the user
creates from an @Autowired @OAuth2Context will also forward
tokens. This feature is implemented by default as an MVC handler
interceptor, so it only works in Spring MVC. If you are not using MVC
you could use a custom filter or AOP interceptor wrapping an
AccessTokenContextRelay to provide the same feature.
Here’s a basic example showing the use of an autowired rest template created elsewhere ("foo.com" is a Resource Server accepting the same tokens as the surrounding app):
@Autowired
private OAuth2RestOperations restTemplate;
@RequestMapping("/relay")
public String relay() {
ResponseEntity<String> response =
restTemplate.getForEntity("https://foo.com/bar", String.class);
return "Success! (" + response.getBody() + ")";
}
If you don’t want to forward tokens (and that is a valid
choice, since you might want to act as yourself, rather than the
client that sent you the token), then you only need to create your own
OAuth2Context instead of autowiring the default one.
Feign clients will also pick up an interceptor that uses the
OAuth2ClientContext if it is available, so they should also do a
token relay anywhere where a RestTemplate would.
You can control the authorization behaviour downstream of an
@EnableZuulProxy through the proxy.auth.* settings. Example:
proxy:
auth:
routes:
customers: oauth2
stores: passthru
recommendations: none
In this example the "customers" service gets an OAuth2 token relay, the "stores" service gets a passthrough (the authorization header is just passed downstream), and the "recommendations" service has its authorization header removed. The default behaviour is to do a token relay if there is a token available, and passthru otherwise.
See ProxyAuthenticationProperties for full details.
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).
The spring-cloud-cloudfoundry-web project provides basic support for
some enhanced features of webapps in Cloud Foundry: binding
automatically to single-sign-on services and optionally enabling
sticky routing for discovery.
The spring-cloud-cloudfoundry-discovery project provides an
implementation of Spring Cloud Commons DiscoveryClient so you can
@EnableDiscoveryClient and provide your credentials as
spring.cloud.cloudfoundry.discovery.[email,password] and then you
can use the DiscoveryClient directly or via a LoadBalancerClient
(also *.url if you are not connecting to
Pivotal Web Services).
The first time you use it the discovery client might be slow owing to the fact that it has to get an access token from Cloud Foundry.
Here’s a Spring Cloud app with Cloud Foundry discovery:
@Grab('org.springframework.cloud:spring-cloud-cloudfoundry')
@RestController
@EnableDiscoveryClient
class Application {
@Autowired
DiscoveryClient client
@RequestMapping('/')
String home() {
'Hello from ' + client.getLocalServiceInstance()
}
}
If you run it without any service bindings:
$ spring jar app.jar app.groovy $ cf push -p app.jar
It will show its app name in the home page.
The DiscoveryClient can lists all the apps in a space, according to
the credentials it is authenticated with, where the space defaults to
the one the client is running in (if any). If neither org nor space
are configured, they default per the user’s profile in Cloud Foundry.
|
Note
|
All of the OAuth2 SSO and resource server features moved to Spring Boot in version 1.3. You can find documentation in the Spring Boot user guide. |
This project provides automatic binding from CloudFoundry service
credentials to the Spring Boot features. If you have a CloudFoundry
service called "sso", for instance, with credentials containing
"client_id", "client_secret" and "auth_domain", it will bind
automatically to the Spring OAuth2 client that you enable with
@EnableOAuth2Sso (from Spring Boot). The name of the service can be
parameterized using spring.oauth2.sso.serviceId.
Leader election allows application to work together with other
applications to coordinate a cluster leadership via a third party system.
Currently we provide integrations with zookeeper, hazelcast and etcd.
From user perspective election is working via interfaces
org.springframework.cloud.cluster.leader.Candidate and
org.springframework.cloud.cluster.leader.Context. Candidate
contains access to leadership’s role and id and also have methods
onGranted and onRevoked. These callback methods are useful if
default Candidate implementation is changed.
Leader election is auto-configured if spring-cloud-cluster-autoconfigure
and either spring-cloud-cluster-hazelcast, spring-cloud-cluster-zookeeper
or spring-cloud-cluster-etcd jars are found from a classpath. In
case where both jars are found leader election is created using both
systems. See sections Zookeeper,
Hazelcast and
Etcd for more
information about a created beans.
Default Candidate created from auto-configuration is
org.springframework.cloud.cluster.leader.DefaultCandidate which
currently only logs granted and revoked events.
If there’s a need for disable all leader related auto-configuration,
a spring.cloud.cluster.leader.enabled can be set to false which
then allows to do manual configuration even if the jars an on a
classpath. Properties spring.cloud.cluster.leader.id and
spring.cloud.cluster.leader.role can be used to set default
identifier and role.
If you are interested to simple get notification of granted and
revoked events one option is to attach event listener into spring
application context. Events OnGrantedEvent and OnRevokedEvent are
sent as spring event objects.
Simply create your own event listener class:
class MyEventListener implements ApplicationListener<AbstractLeaderEvent> {
@Override
public void onApplicationEvent(AbstractLeaderEvent event) {
// do something with OnGrantedEvent or OnRevokedEvent
}
}
and then create it as a bean.
@Configuration
static class Config {
@Bean
public MyEventListener myEventListener() {
return new MyEventListener();
}
}
For simply log events you can also use a utility class
LoggingListener which allows easy configuration.
import org.springframework.cloud.cluster.leader.event.LoggingListener;
@Configuration
static class Config {
@Bean
public LoggingListener loggingListener() {
return new LoggingListener("info");
}
}
Candidate implementation for zookeeper is created with a bean name
zookeeperLeaderCandidate which can be used to override the one
created during auto-configuration.
Zookeeper based election can be explicitly disabled using property
spring.cloud.cluster.zookeeper.leader.enabled.
Other properties spring.cloud.cluster.zookeeper.namespace and
spring.cloud.cluster.zookeeper.connect can be used to set the
zookeeper base namespace path and connect string.
Candidate implementation for hazelcast is created with a bean name
hazelcastLeaderCandidate which can be used to override the one
created during auto-configuration.
Hazelcast based election can be explicitly disabled using property
spring.cloud.cluster.hazelcast.leader.enabled. If you want to provide xml
based configuration for Hazelcast instance use property
spring.cloud.cluster.hazelcast.config-location to tell location of a
Hazelcast xml configuration file. config-location is a normal spring
Resource.
Candidate implementation for etcd is created with a bean name
etcdLeaderCandidate which can be used to override the one
created during auto-configuration.
Etcd based election can be explicitly disabled using property
spring.cloud.cluster.etcd.leader.enabled.
Multiple etcd cluster uris can be specified using property
spring.cloud.cluster.etcd.connect
| Name | Default | Description |
|---|---|---|
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 true then the GCM algorithm is applied to the AES encrypted bytes. Default is false (in which case "standard" CBC is used instead). Once it is set do not change it (or existing ciphers will not a decryptable). |
endpoints.bus.enabled |
||
endpoints.bus.id |
||
endpoints.bus.sensitive |
||
endpoints.consul.enabled |
||
endpoints.consul.id |
||
endpoints.consul.sensitive |
||
endpoints.features.enabled |
||
endpoints.features.id |
||
endpoints.features.sensitive |
||
endpoints.pause.enabled |
||
endpoints.pause.id |
||
endpoints.pause.sensitive |
||
endpoints.refresh.enabled |
||
endpoints.refresh.id |
||
endpoints.refresh.sensitive |
||
endpoints.restart.enabled |
||
endpoints.restart.id |
||
endpoints.restart.pause-endpoint.enabled |
||
endpoints.restart.pause-endpoint.id |
||
endpoints.restart.pause-endpoint.sensitive |
||
endpoints.restart.resume-endpoint.enabled |
||
endpoints.restart.resume-endpoint.id |
||
endpoints.restart.resume-endpoint.sensitive |
||
endpoints.restart.sensitive |
||
endpoints.restart.timeout |
0 |
|
endpoints.resume.enabled |
||
endpoints.resume.id |
||
endpoints.resume.sensitive |
||
eureka.client.allow-redirects |
false |
Indicates whether server can redirect a client request to a backup server/cluster. If set to false, the server will handle the request directly, If set to true, it may send HTTP redirect to the client, with a new server location. |
eureka.client.availability-zones |
Gets the list of availability zones (used in AWS data centers) for the region in which this instance resides. The changes are effective at runtime at the next registry fetch cycle as specified by registryFetchIntervalSeconds. |
|
eureka.client.backup-registry-impl |
Gets the name of the implementation which implements BackupRegistry to fetch the registry information as a fall back option for only the first time when the eureka client starts. This may be needed for applications which needs additional resiliency for registry information without which it cannot operate. |
|
eureka.client.cache-refresh-executor-exponential-back-off-bound |
10 |
Cache refresh executor exponential back off related property. It is a maximum multiplier value for retry delay, in case where a sequence of timeouts occurred. |
eureka.client.cache-refresh-executor-thread-pool-size |
2 |
The thread pool size for the cacheRefreshExecutor to initialise with |
eureka.client.client-data-accept |
EurekaAccept name for client data accept |
|
eureka.client.decoder-name |
This is a transient config and once the latest codecs are stable, can be removed (as there will only be one) |
|
eureka.client.disable-delta |
false |
Indicates whether the eureka client should disable fetching of delta and should rather resort to getting the full registry information. Note that the delta fetches can reduce the traffic tremendously, because the rate of change with the eureka server is normally much lower than the rate of fetches. The changes are effective at runtime at the next registry fetch cycle as specified by registryFetchIntervalSeconds |
eureka.client.dollar-replacement |
_- |
Get a replacement string for Dollar sign <code>$</code> during serializing/deserializing information in eureka server. |
eureka.client.enabled |
true |
Flag to indicate that the Eureka client is enabled. |
eureka.client.encoder-name |
This is a transient config and once the latest codecs are stable, can be removed (as there will only be one) |
|
eureka.client.escape-char-replacement |
__ |
Get a replacement string for underscore sign <code>_</code> during serializing/deserializing information in eureka server. |
eureka.client.eureka-connection-idle-timeout-seconds |
30 |
Indicates how much time (in seconds) that the HTTP connections to eureka server can stay idle before it can be closed. In the AWS environment, it is recommended that the values is 30 seconds or less, since the firewall cleans up the connection information after a few mins leaving the connection hanging in limbo |
eureka.client.eureka-server-connect-timeout-seconds |
5 |
Indicates how long to wait (in seconds) before a connection to eureka server needs to timeout. Note that the connections in the client are pooled by org.apache.http.client.HttpClient and this setting affects the actual connection creation and also the wait time to get the connection from the pool. |
eureka.client.eureka-server-dnsname |
Gets the DNS name to be queried to get the list of eureka servers.This information is not required if the contract returns the service urls by implementing serviceUrls. The DNS mechanism is used when useDnsForFetchingServiceUrls is set to true and the eureka client expects the DNS to configured a certain way so that it can fetch changing eureka servers dynamically. The changes are effective at runtime. |
|
eureka.client.eureka-server-port |
Gets the port to be used to construct the service url to contact eureka server when the list of eureka servers come from the DNS.This information is not required if the contract returns the service urls eurekaServerServiceUrls(String). The DNS mechanism is used when useDnsForFetchingServiceUrls is set to true and the eureka client expects the DNS to configured a certain way so that it can fetch changing eureka servers dynamically. The changes are effective at runtime. |
|
eureka.client.eureka-server-read-timeout-seconds |
8 |
Indicates how long to wait (in seconds) before a read from eureka server needs to timeout. |
eureka.client.eureka-server-total-connections |
200 |
Gets the total number of connections that is allowed from eureka client to all eureka servers. |
eureka.client.eureka-server-total-connections-per-host |
50 |
Gets the total number of connections that is allowed from eureka client to a eureka server host. |
eureka.client.eureka-server-urlcontext |
Gets the URL context to be used to construct the service url to contact eureka server when the list of eureka servers come from the DNS. This information is not required if the contract returns the service urls from eurekaServerServiceUrls. The DNS mechanism is used when useDnsForFetchingServiceUrls is set to true and the eureka client expects the DNS to configured a certain way so that it can fetch changing eureka servers dynamically. The changes are effective at runtime. |
|
eureka.client.eureka-service-url-poll-interval-seconds |
0 |
Indicates how often(in seconds) to poll for changes to eureka server information. Eureka servers could be added or removed and this setting controls how soon the eureka clients should know about it. |
eureka.client.fetch-registry |
true |
Indicates whether this client should fetch eureka registry information from eureka server. |
eureka.client.fetch-remote-regions-registry |
Comma separated list of regions for which the eureka registry information will be fetched. It is mandatory to define the availability zones for each of these regions as returned by availabilityZones. Failing to do so, will result in failure of discovery client startup. |
|
eureka.client.filter-only-up-instances |
true |
Indicates whether to get the applications after filtering the applications for instances with only InstanceStatus UP states. |
eureka.client.g-zip-content |
true |
Indicates whether the content fetched from eureka server has to be compressed whenever it is supported by the server. The registry information from the eureka server is compressed for optimum network traffic. |
eureka.client.heartbeat-executor-exponential-back-off-bound |
10 |
Heartbeat executor exponential back off related property. It is a maximum multiplier value for retry delay, in case where a sequence of timeouts occurred. |
eureka.client.heartbeat-executor-thread-pool-size |
2 |
The thread pool size for the heartbeatExecutor to initialise with |
eureka.client.initial-instance-info-replication-interval-seconds |
40 |
Indicates how long initially (in seconds) to replicate instance info to the eureka server |
eureka.client.instance-info-replication-interval-seconds |
30 |
Indicates how often(in seconds) to replicate instance changes to be replicated to the eureka server. |
eureka.client.log-delta-diff |
false |
Indicates whether to log differences between the eureka server and the eureka client in terms of registry information. Eureka client tries to retrieve only delta changes from eureka server to minimize network traffic. After receiving the deltas, eureka client reconciles the information from the server to verify it has not missed out some information. Reconciliation failures could happen when the client has had network issues communicating to server.If the reconciliation fails, eureka client gets the full registry information. While getting the full registry information, the eureka client can log the differences between the client and the server and this setting controls that. The changes are effective at runtime at the next registry fetch cycle as specified by registryFetchIntervalSecondsr |
eureka.client.on-demand-update-status-change |
true |
If set to true, local status updates via ApplicationInfoManager will trigger on-demand (but rate limited) register/updates to remote eureka servers |
eureka.client.prefer-same-zone-eureka |
true |
Indicates whether or not this instance should try to use the eureka server in the same zone for latency and/or other reason. Ideally eureka clients are configured to talk to servers in the same zone The changes are effective at runtime at the next registry fetch cycle as specified by registryFetchIntervalSeconds |
eureka.client.property-resolver |
||
eureka.client.proxy-host |
Gets the proxy host to eureka server if any. |
|
eureka.client.proxy-password |
Gets the proxy password if any. |
|
eureka.client.proxy-port |
Gets the proxy port to eureka server if any. |
|
eureka.client.proxy-user-name |
Gets the proxy user name if any. |
|
eureka.client.region |
us-east-1 |
Gets the region (used in AWS datacenters) where this instance resides. |
eureka.client.register-with-eureka |
true |
Indicates whether or not this instance should register its information with eureka server for discovery by others. In some cases, you do not want your instances to be discovered whereas you just want do discover other instances. |
eureka.client.registry-fetch-interval-seconds |
30 |
Indicates how often(in seconds) to fetch the registry information from the eureka server. |
eureka.client.registry-refresh-single-vip-address |
Indicates whether the client is only interested in the registry information for a single VIP. |
|
eureka.client.service-url |
Map of availability zone to list of fully qualified URLs to communicate with eureka server. Each value can be a single URL or a comma separated list of alternative locations. Typically the eureka server URLs carry protocol,host,port,context and version information if any. Example: http://ec2-256-156-243-129.compute-1.amazonaws.com:7001/eureka/ The changes are effective at runtime at the next service url refresh cycle as specified by eurekaServiceUrlPollIntervalSeconds. |
|
eureka.client.transport |
||
eureka.client.use-dns-for-fetching-service-urls |
false |
Indicates whether the eureka client should use the DNS mechanism to fetch a list of eureka servers to talk to. When the DNS name is updated to have additional servers, that information is used immediately after the eureka client polls for that information as specified in eurekaServiceUrlPollIntervalSeconds. Alternatively, the service urls can be returned serviceUrls, but the users should implement their own mechanism to return the updated list in case of changes. The changes are effective at runtime. |
eureka.dashboard.enabled |
true |
Flag to enable the Eureka dashboard. Default true. |
eureka.dashboard.path |
/ |
The path to the Eureka dashboard (relative to the servlet path). Defaults to "/". |
eureka.instance.a-sgname |
Gets the AWS autoscaling group name associated with this instance. This information is specifically used in an AWS environment to automatically put an instance out of service after the instance is launched and it has been disabled for traffic.. |
|
eureka.instance.app-group-name |
Get the name of the application group to be registered with eureka. |
|
eureka.instance.appname |
unknown |
Get the name of the application to be registered with eureka. |
eureka.instance.data-center-info |
Returns the data center this instance is deployed. This information is used to get some AWS specific instance information if the instance is deployed in AWS. |
|
eureka.instance.default-address-resolution-order |
[] |
|
eureka.instance.health-check-url |
Gets the absolute health check page URL for this instance. The users can provide the healthCheckUrlPath if the health check page resides in the same instance talking to eureka, else in the cases where the instance is a proxy for some other server, users can provide the full URL. If the full URL is provided it takes precedence. <p> It is normally used for making educated decisions based on the health of the instance - for example, it can be used to determine whether to proceed deployments to an entire farm or stop the deployments without causing further damage. The full URL should follow the format http://${eureka.hostname}:7001/ where the value ${eureka.hostname} is replaced at runtime. |
|
eureka.instance.health-check-url-path |
/health |
Gets the relative health check URL path for this instance. The health check page URL is then constructed out of the hostname and the type of communication - secure or unsecure as specified in securePort and nonSecurePort. It is normally used for making educated decisions based on the health of the instance - for example, it can be used to determine whether to proceed deployments to an entire farm or stop the deployments without causing further damage. |
eureka.instance.home-page-url |
Gets the absolute home page URL for this instance. The users can provide the homePageUrlPath if the home page resides in the same instance talking to eureka, else in the cases where the instance is a proxy for some other server, users can provide the full URL. If the full URL is provided it takes precedence. It is normally used for informational purposes for other services to use it as a landing page. The full URL should follow the format http://${eureka.hostname}:7001/ where the value ${eureka.hostname} is replaced at runtime. |
|
eureka.instance.home-page-url-path |
/ |
Gets the relative home page URL Path for this instance. The home page URL is then constructed out of the hostName and the type of communication - secure or unsecure. It is normally used for informational purposes for other services to use it as a landing page. |
eureka.instance.host-info |
||
eureka.instance.hostname |
The hostname if it can be determined at configuration time (otherwise it will be guessed from OS primitives). |
|
eureka.instance.inet-utils |
||
eureka.instance.initial-status |
Initial status to register with rmeote Eureka server. |
|
eureka.instance.instance-enabled-onit |
false |
Indicates whether the instance should be enabled for taking traffic as soon as it is registered with eureka. Sometimes the application might need to do some pre-processing before it is ready to take traffic. |
eureka.instance.instance-id |
Get the unique Id (within the scope of the appName) of this instance to be registered with eureka. |
|
eureka.instance.ip-address |
Get the IPAdress of the instance. This information is for academic purposes only as the communication from other instances primarily happen using the information supplied in {@link #getHostName(boolean)}. |
|
eureka.instance.lease-expiration-duration-in-seconds |
90 |
Indicates the time in seconds that the eureka server waits since it received the last heartbeat before it can remove this instance from its view and there by disallowing traffic to this instance. Setting this value too long could mean that the traffic could be routed to the instance even though the instance is not alive. Setting this value too small could mean, the instance may be taken out of traffic because of temporary network glitches.This value to be set to atleast higher than the value specified in leaseRenewalIntervalInSeconds. |
eureka.instance.lease-renewal-interval-in-seconds |
30 |
Indicates how often (in seconds) the eureka client needs to send heartbeats to eureka server to indicate that it is still alive. If the heartbeats are not received for the period specified in leaseExpirationDurationInSeconds, eureka server will remove the instance from its view, there by disallowing traffic to this instance. Note that the instance could still not take traffic if it implements HealthCheckCallback and then decides to make itself unavailable. |
eureka.instance.metadata-map |
Gets the metadata name/value pairs associated with this instance. This information is sent to eureka server and can be used by other instances. |
|
eureka.instance.namespace |
eureka |
Get the namespace used to find properties. Ignored in Spring Cloud. |
eureka.instance.non-secure-port |
80 |
Get the non-secure port on which the instance should receive traffic. |
eureka.instance.non-secure-port-enabled |
true |
Indicates whether the non-secure port should be enabled for traffic or not. |
eureka.instance.prefer-ip-address |
false |
Flag to say that, when guessing a hostname, the IP address of the server should be used in prference to the hostname reported by the OS. |
eureka.instance.secure-health-check-url |
Gets the absolute secure health check page URL for this instance. The users can provide the secureHealthCheckUrl if the health check page resides in the same instance talking to eureka, else in the cases where the instance is a proxy for some other server, users can provide the full URL. If the full URL is provided it takes precedence. <p> It is normally used for making educated decisions based on the health of the instance - for example, it can be used to determine whether to proceed deployments to an entire farm or stop the deployments without causing further damage. The full URL should follow the format http://${eureka.hostname}:7001/ where the value ${eureka.hostname} is replaced at runtime. |
|
eureka.instance.secure-port |
443 |
Get the Secure port on which the instance should receive traffic. |
eureka.instance.secure-port-enabled |
false |
Indicates whether the secure port should be enabled for traffic or not. |
eureka.instance.secure-virtual-host-name |
Gets the secure virtual host name defined for this instance. This is typically the way other instance would find this instance by using the secure virtual host name.Think of this as similar to the fully qualified domain name, that the users of your services will need to find this instance. |
|
eureka.instance.status-page-url |
Gets the absolute status page URL path for this instance. The users can provide the statusPageUrlPath if the status page resides in the same instance talking to eureka, else in the cases where the instance is a proxy for some other server, users can provide the full URL. If the full URL is provided it takes precedence. It is normally used for informational purposes for other services to find about the status of this instance. Users can provide a simple HTML indicating what is the current status of the instance. |
|
eureka.instance.status-page-url-path |
/info |
Gets the relative status page URL path for this instance. The status page URL is then constructed out of the hostName and the type of communication - secure or unsecure as specified in securePort and nonSecurePort. It is normally used for informational purposes for other services to find about the status of this instance. Users can provide a simple HTML indicating what is the current status of the instance. |
eureka.instance.virtual-host-name |
Gets the virtual host name defined for this instance. This is typically the way other instance would find this instance by using the virtual host name.Think of this as similar to the fully qualified domain name, that the users of your services will need to find this instance. |
|
eureka.server.a-sgcache-expiry-timeout-ms |
0 |
|
eureka.server.a-sgquery-timeout-ms |
300 |
|
eureka.server.a-sgupdate-interval-ms |
0 |
|
eureka.server.a-wsaccess-id |
||
eureka.server.a-wssecret-key |
||
eureka.server.batch-replication |
false |
|
eureka.server.binding-strategy |
||
eureka.server.delta-retention-timer-interval-in-ms |
0 |
|
eureka.server.disable-delta |
false |
|
eureka.server.disable-delta-for-remote-regions |
false |
|
eureka.server.disable-transparent-fallback-to-other-region |
false |
|
eureka.server.e-ipbind-rebind-retries |
3 |
|
eureka.server.e-ipbinding-retry-interval-ms |
0 |
|
eureka.server.e-ipbinding-retry-interval-ms-when-unbound |
0 |
|
eureka.server.enable-replicated-request-compression |
false |
|
eureka.server.enable-self-preservation |
true |
|
eureka.server.eviction-interval-timer-in-ms |
0 |
|
eureka.server.g-zip-content-from-remote-region |
true |
|
eureka.server.json-codec-name |
||
eureka.server.list-auto-scaling-groups-role-name |
ListAutoScalingGroups |
|
eureka.server.log-identity-headers |
true |
|
eureka.server.max-elements-in-peer-replication-pool |
10000 |
|
eureka.server.max-elements-in-status-replication-pool |
10000 |
|
eureka.server.max-idle-thread-age-in-minutes-for-peer-replication |
15 |
|
eureka.server.max-idle-thread-in-minutes-age-for-status-replication |
10 |
|
eureka.server.max-threads-for-peer-replication |
20 |
|
eureka.server.max-threads-for-status-replication |
1 |
|
eureka.server.max-time-for-replication |
30000 |
|
eureka.server.min-threads-for-peer-replication |
5 |
|
eureka.server.min-threads-for-status-replication |
1 |
|
eureka.server.number-of-replication-retries |
5 |
|
eureka.server.peer-eureka-nodes-update-interval-ms |
0 |
|
eureka.server.peer-eureka-status-refresh-time-interval-ms |
0 |
|
eureka.server.peer-node-connect-timeout-ms |
200 |
|
eureka.server.peer-node-connection-idle-timeout-seconds |
30 |
|
eureka.server.peer-node-read-timeout-ms |
200 |
|
eureka.server.peer-node-total-connections |
1000 |
|
eureka.server.peer-node-total-connections-per-host |
500 |
|
eureka.server.prime-aws-replica-connections |
true |
|
eureka.server.property-resolver |
||
eureka.server.rate-limiter-burst-size |
10 |
|
eureka.server.rate-limiter-enabled |
false |
|
eureka.server.rate-limiter-full-fetch-average-rate |
100 |
|
eureka.server.rate-limiter-privileged-clients |
||
eureka.server.rate-limiter-registry-fetch-average-rate |
500 |
|
eureka.server.rate-limiter-throttle-standard-clients |
false |
|
eureka.server.registry-sync-retries |
0 |
|
eureka.server.registry-sync-retry-wait-ms |
0 |
|
eureka.server.remote-region-app-whitelist |
||
eureka.server.remote-region-connect-timeout-ms |
1000 |
|
eureka.server.remote-region-connection-idle-timeout-seconds |
30 |
|
eureka.server.remote-region-fetch-thread-pool-size |
20 |
|
eureka.server.remote-region-read-timeout-ms |
1000 |
|
eureka.server.remote-region-registry-fetch-interval |
30 |
|
eureka.server.remote-region-total-connections |
1000 |
|
eureka.server.remote-region-total-connections-per-host |
500 |
|
eureka.server.remote-region-trust-store |
||
eureka.server.remote-region-trust-store-password |
changeit |
|
eureka.server.remote-region-urls |
||
eureka.server.remote-region-urls-with-name |
||
eureka.server.renewal-percent-threshold |
0.85 |
|
eureka.server.renewal-threshold-update-interval-ms |
0 |
|
eureka.server.response-cache-auto-expiration-in-seconds |
180 |
|
eureka.server.response-cache-update-interval-ms |
0 |
|
eureka.server.retention-time-in-msin-delta-queue |
0 |
|
eureka.server.route53-bind-rebind-retries |
3 |
|
eureka.server.route53-binding-retry-interval-ms |
0 |
|
eureka.server.route53-domain-ttl |
30 |
|
eureka.server.sync-when-timestamp-differs |
true |
|
eureka.server.use-read-only-response-cache |
true |
|
eureka.server.wait-time-in-ms-when-sync-empty |
0 |
|
eureka.server.xml-codec-name |
||
feign.compression.request.mime-types |
[text/xml, application/xml, application/json] |
The list of supported mime types. |
feign.compression.request.min-request-size |
2048 |
The minimum threshold content size. |
health.config.enabled |
false |
Flag to indicate that the config server health indicator should be installed. |
health.hystrix.enabled |
false |
Flag to inidicate that the hystrix health indicator should be installed. |
netflix.atlas.batch-size |
10000 |
|
netflix.atlas.enabled |
true |
|
netflix.atlas.uri |
||
proxy.auth.load-balanced |
false |
|
proxy.auth.routes |
Authentication strategy per route. |
|
spring.cloud.bus.ack.destination-service |
Service that wants to listen to acks. By default null (meaning all services). |
|
spring.cloud.bus.ack.enabled |
true |
Flag to switch off acks (default on). |
spring.cloud.bus.destination |
springCloudBus |
Name of Spring Cloud Stream destination for messages. |
spring.cloud.bus.enabled |
true |
Flag to indicate that the bus is enabled. |
spring.cloud.bus.env.enabled |
true |
Flag to switch off environment change events (default on). |
spring.cloud.bus.refresh.enabled |
true |
Flag to switch off refresh events (default on). |
spring.cloud.bus.trace.enabled |
false |
Flag to switch on tracing of acks (default off). |
spring.cloud.cloudfoundry.discovery.email |
Email address of user to authenticate. |
|
spring.cloud.cloudfoundry.discovery.enabled |
true |
Flag to indicate that discovery is enabled. |
spring.cloud.cloudfoundry.discovery.password |
Password for user to authenticate and obtain token. |
|
spring.cloud.cloudfoundry.discovery.url |
URL of Cloud Foundry API (Cloud Controller). |
|
spring.cloud.config.allow-override |
true |
Flag to indicate that {@link #isSystemPropertiesOverride() systemPropertiesOverride} can be used. Set to false to prevent users from changing the default accidentally. Default true. |
spring.cloud.config.discovery.enabled |
false |
Flag to indicate that config server discovery is enabled (config server URL will be looked up via discovery). |
spring.cloud.config.discovery.service-id |
CONFIGSERVER |
Service id to locate config server. |
spring.cloud.config.enabled |
true |
Flag to say that remote configuration is enabled. Default true; |
spring.cloud.config.fail-fast |
false |
Flag to indicate that failure to connect to the server is fatal (default false). |
spring.cloud.config.label |
The label name to use to pull remote configuration properties. The default is set on the server (generally "master" for a git based server). |
|
spring.cloud.config.name |
Name of application used to fetch remote properties. |
|
spring.cloud.config.override-none |
false |
Flag to indicate that when {@link #setAll [Page truncated to keep GeezerVison snappy.] |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |