1.2.0.RELEASE
the project provides consul integration for spring boot applications by automatically configuring and binding to the spring environment and other spring programming model idioms. with a few simple annotations, you can quickly enable and configure common patterns in your application and build large distributed systems using consul-based components. The modes provided include service discovery, control bus and configuration. Intelligent Routing (Zuul) and Client load Balancing (Ribbon), Circuit breakers (Hystrix) are provided through integration with spring Cloud Netflix.
Installing Consul
Please see Installation Documentation get instructions on how to install consul.
Consul Agent
all spring Cloud Consul applications must be able to use the Consul agent client. By default, the proxy client is expected to be located localhost:8500
. For more information about How to start a proxy client and how to connect to a cluster of consul agent servers , see the proxy documentation . for developers, after the consul has been installed, you can start the consul Agent with the following command:
./src/main/bash/local_run_consul.sh
This will start the proxy for server mode on port 8500, where the UI can be found on/HTTP localhost:8500
Service discovery and consul
Service Discovery is one of the key principles of micro-service architecture. trying to configure each client or some form of convention can be very difficult and very fragile. Consul provides service discovery services through HTTP APIs and DNS . Spring Cloud Consul uses the HTTP API for service registration and discovery. This does not prevent non-spring cloud applications from taking advantage of the DNS interface. The consul proxy server runs in a cluster that communicates through the gossip protocol and uses Raft Protocol protocol .
How to activate
to activate the Consul service discovery, use org.springframework.cloud
spring-cloud-starter-consul-discovery
the initiator of the group and artifact IDs. for More information about using the current Spring Cloud train setup build system, see The Spring Cloud computing page .
Register Consul
When a client registers consul, it provides metadata about itself, such as host and Port, ID, name, and label. By default, an HTTP check is created that consul hits the endpoint every 10 seconds /health
. If the health check fails, the service instance is marked as critical.
Example Consul client:
@SpringBootApplication@EnableDiscoveryClient@RestControllerpublic class Application { @RequestMapping("/") public String home() { return "Hello world"; } public static void main(String[] args) { new SpringApplicationBuilder(Application.class).web(true).run(args); }}
(that is, the fully normal spring boot application). If the consul client is located localhost:8500
outside the location, it needs to be configured to locate the client. Example:
application.yml
spring: cloud: consul: host: localhost port: 8500
Warning |
If you use Spring Cloud Consul Config , the above values will need to be placed bootstrap.yml instead application.yml of in. |
From Environment
The default service name obtained, the instance ID and port are ${spring.application.name}
, respectively, the spring context ID and ${server.port}
.
@EnableDiscoveryClient
Make the Application Consul "service" (that is, registering itself) and "client" (that is, you can query consul to find other services).
http Health Check
The health Check for a consul instance defaults to "/", which is the default location for useful endpoints in spring Boot actuator applications. If you use a non-default context path or a servlet path (for example server.servletPath=/foo
) or manage the endpoint path (for example management.context-path=/admin
)), you need to change these, even for the executor application. You can also configure the interval that Consul uses to check the health endpoint. "10s" and "1m" represent 10 seconds and 1 minutes, respectively. Example:
application.yml
spring: cloud: consul: discovery: healthCheckPath: ${management.context-path}/health healthCheckInterval: 15s
meta data and consul tags
Consul does not yet support service metadata. Spring Cloud ServiceInstance
has a Map<String, String> metadata
field. Spring Cloud Consul uses consul tags to approximate metadata until consul formally supports metadata. labels with a key=value
form are split and used as Map
keys and values, respectively. labels that do not have =
an equality symbol are used as both the key and the value.
application.yml
spring: cloud: consul: discovery: tags: foo=bar, baz
The above configuration will result foo→bar
in a map with and baz→baz
.
make Consul instance ID unique
by default, a consular entity registers an ID equal to its spring application context ID. by Default, the Spring app context ID is ${spring.application.name}:comma,separated,profiles:${server.port}
. In most cases, this will allow multiple instances of a service to run on a single machine. If further uniqueness is required, use spring Cloud to spring.cloud.consul.discovery.instanceId
override this by providing a unique identity in. For example:
application.yml
spring: cloud: consul: discovery: instanceId: ${spring.application.name}:${vcap.application.instance_id:${spring.application.instance_id:${random.value}}}
with this metadata and multiple service instances deployed on localhost, the random values will be there to make the instance unique. in Cloudfoundry, it is vcap.application.instance_id
automatically populated in the spring boot application, so no random values are required.
using Discoveryclient
Spring Cloud Support Feign (a Rest client builder) that also supports Spring RestTemplate
Use the logical service name instead of the actual URL.
You can also use org.springframework.cloud.client.discovery.DiscoveryClient
it to provide simple APIs for Netflix's non-specific discovery clients, such as
@Autowiredprivate DiscoveryClient discoveryClient;public String serviceUrl() { List<ServiceInstance> list = discoveryClient.getInstances("STORES"); if (list != null && list.size() > 0 ) { return list.get(0).getUri(); } return null;}
distributed configuration with consul
The Consul provides used to store configuration and other meta-data of the key/value store . Spring Cloud Consul config is an alternative to config server and client . in a special "boot" phase, the configuration is loaded into the spring environment. By default, the configuration is stored in a /config
folder. Create multiple instances based on the name of the application and the active configuration file that simulates the properties of the Spring Cloud config sequence PropertySource
. For example, an application named "TestApp" and a "dev" profile create the following property sources:
config/testApp,dev/config/testApp/config/application,dev/config/application/
The most specific source of property is located at the top, the bottom most not specific. Properties is a config/application
folder for all applications that are configured with Consul. the config/testApp
properties in the folder apply only to service instances named "TestApp".
The configuration is currently read when the application starts. sending HTTP POST to /refresh
will cause the configuration to reload. viewing key-value storage (consul support) is not possible at this time, but will be a complement to this project in the future.
How to activate
to start using the consul configuration, use org.springframework.cloud
spring-cloud-starter-consul-config
the initiator of the group and artifact IDs. for More information about using the current Spring Cloud train setup build system, see The Spring Cloud computing page .
This will enable automatic configuration that will configure the spring Cloud Consul configuration.
Custom
You can customize the consul configuration with the following properties:
bootstrap.yml
spring: cloud: consul: config: enabled: true prefix: configuration defaultContext: apps profileSeparator: ‘::‘
enabled
Setting this value to "false" disables the consul configuration
prefix
Set a basic folder for configuration values
defaultContext
Set the folder name used by all applications
profileSeparator
Sets the value of the delimiter used to separate the profile name in the property source using the configuration file
Configuration Observation
The Consul configuration observation function allows the use of consular Guard Key Prefix the ability . Config Watch blocks consul HTTP API calls to determine whether any relevant configuration data has changed for the current application. If there is new configuration data, a refresh event is published. This is equivalent to invoking the /refresh
executor endpoint.
to change the frequency of the Config watch call spring.cloud.consul.config.watch.delay
. the default value is 1000, in milliseconds.
Disables the Config Watch collection spring.cloud.consul.config.watch.enabled=false
.
Yaml or Properties configuration
It may be more convenient to store a set of properties in the Yaml or properties format relative to a single key/value pair. spring.cloud.consul.config.format
Set the property to YAML
or PROPERTIES
. For example, using Yaml:
bootstrap.yml
spring: cloud: consul: config: format: YAML
Yaml must be set in the appropriate data
key. The default value above using the key will look like this:
config/testApp,dev/dataconfig/testApp/dataconfig/application,dev/dataconfig/application/data
You can store a YAML document in any of these keys.
You can use the spring.cloud.consul.config.data-key
change data key.
Git2consul and Configuration
Git2consul is a consul community project that loads files from a git repository into individual keys to consul. By default, the name of the key is the name of the file. .yml
.properties
the Yaml and properties files with the file name extension and are supported respectively. spring.cloud.consul.config.format
Set the property to FILES
. For example:
bootstrap.yml
spring: cloud: consul: config: format: FILES
Given /config
the following key, the development
configuration file and application name are foo
:
.gitignoreapplication.ymlbar.propertiesfoo-development.propertiesfoo-production.ymlfoo.propertiesmaster.ref
The following attribute sources will be created:
config/foo-development.propertiesconfig/foo.propertiesconfig/application.yml
The value of each key needs to be a properly formatted YAML or properties file.
Fast Failure
in some cases, such as local development or some test scenarios, it may be convenient to not fail if the consul cannot be configured. bootstrap.yml
setting in spring.cloud.consul.config.failFast=false
will cause the configuration module to record a warning instead of throwing an exception. This will allow the application to continue to start normally.
Consul Retry
If you want your application to start with an occasional inability to use the reseller, you can ask you to continue trying after a failure. you need to add and in your Classpath spring-retry
spring-boot-starter-aop
. the default behavior is to retry 6 times, with an initial backoff interval of 1000ms and an exponential multiplier of 1.1 for subsequent backoff. You can use spring.cloud.consul.retry.*
configuration properties to configure these properties (and others). This applies to spring Cloud Consul configuration and Discovery registration.
Tips |
to fully control the retry, use the ID of "consulretryinterceptor" to add RetryOperationsInterceptor the type @Bean . Spring Retries has one RetryInterceptorBuilder , which makes it easy to create one. |
Spring Cloud Bus and consulHow to activate
to start using the Consul bus, use org.springframework.cloud
the initiator for group and artifact IDs spring-cloud-starter-consul-bus
. for More information about using the current Spring Cloud train setup build system, see The Spring Cloud computing page .
about the available actuator endpoints and how to send custom messages, Please see Spring Cloud Bus documentation.
circuit breakers and Hystrix
The application can use the Hystrix circuit breaker provided by the spring Cloud Netflix project to include this launcher in Project Pom.xml: spring-cloud-starter-hystrix
. Hystrix does not rely on the Netflix Discovery Client. @EnableHystrix
Comments should be placed on the configuration class (usually the main class). then the method can be protected by a @HystrixCommand
circuit breaker using annotations. for more information, see the documentation .
aggregation using turbine and consul Hystrix metrics
Turbine (provided by the spring Cloud Netflix project) aggregates multiple instances of the hystrix indicator stream, so dashboards can display aggregated views. Turbine uses DiscoveryClient
interfaces to find related instances. to use turbine with spring Cloud Consul, configure the turbine application in a way similar to the following example:
Pom.xml
<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>
Note that the turbine dependency is not the initiator. the Turbo Starter includes support for Netflix Eureka.
application.yml
spring.application.name: turbineapplications: consulhystrixclientturbine: aggregator: clusterConfig: ${applications} appConfig: ${applications}
clusterConfig
and appConfig
parts must match, so it is useful to place a comma-delimited list of service identities in separate configuration properties.
Turbine.java
@EnableTurbine@EnableDiscoveryClient@SpringBootApplicationpublic class Turbine { public static void main(String[] args) { SpringApplication.run(DemoturbinecommonsApplication.class, args); }}
Spring Cloud Consul