From 43765ec4a80c97c80e1027b237c69778b4d53b76 Mon Sep 17 00:00:00 2001
From: Dave Syer
Spring Cloud Config Server supports a single or multiple git -repositories:
+repositories with pattern matching on the application and profile +name. The pattern format is a comma-separated list of +{application}/{profile} names with wildcards (where a pattern
+beginning with a wildcard may need to be quoted). Example:
In the above example, if {application} does not match any of the
-patterns, it will use the default uri defined under
-"spring.cloud.config.server.git.uri". For the "simple" repository, the
-pattern is "simple" (i.e. it only matches one application named "simple").
-The pattern format is a comma-separated list of application names with
-wildcards (a pattern beginning with a wildcard may need to be quoted).
If {application}/{profile} does not match any of the patterns, it
+will use the default uri defined under
+"spring.cloud.config.server.git.uri". In the above example, for the
+"simple" repository, the pattern is simple/* (i.e. it only matches
+one application named "simple" in all profiles). The "local"
+repository matches all application names beginning with "local" in all
+profiles (the /* suffix is added automatically to any pattern that
+doesn’t have a profile matcher).
The pattern property in the repo is actually an array, so you can
+use a YAML array (or [0], [1], etc. suffixes in properties files)
+to bind to multiple patterns. You may need to do this if you are going
+to run apps with multiple profiles. Example:
spring: + cloud: + config: + server: + git: + uri: https://github.com/spring-cloud-samples/config-repo + repos: + development: + pattern: + - */development + - */staging + uri: https://github.com/development/config-repo + staging: + pattern: + - */qa + - */production + uri: https://github.com/staging/config-repo+
|
+ Note
+ |
+
+Spring Cloud will guess that a pattern containing a profile that
+doesn’t end in * implies that you actually want to match a list of
+profiles starting with this pattern (so */staging is a shortcut for
+["*/staging", "*/staging,*"]). This is common where you need to run
+apps in the "development" profile locally but also the "cloud" profile
+remotely, for instance.
+ |
+
Every repository can also optionally store config files in
sub-directories, and patterns to search for those directories can be
specified as searchPaths. For example at the top level:
Encrypted values in a .properties file must not be wrapped in quotes, otherwise the value will not be decrypted:
+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.
|
+ Tip
+ |
+
+If you are testing like this with curl, then use
+--data-urlencode (instead of -d) or set an explicit Content-Type:
+text/plain to make sure curl encodes the data correctly when there
+are special characters ('+' is particularly tricky).
+ |
+
Take the encrypted value and add the {cipher} prefix before you put
it in the YAML or properties file, and before you commit and push it
@@ -1896,8 +1977,108 @@ handle all encryption as well as decryption.
Instead of using the Environment abstraction (or one of the
+alternative representations of it in YAML or properties format) your
+applications might need generic plain text configuration files,
+tailored to their environment. The Config Server provides these
+through an additional endpoint at /{name}/{profile}/{label}/{path}
+where "name", "profile" and "label" have the same meaning as the
+regular environment endpoint, but "path" is a file name
+(e.g. log.xml). The source files for this endpoint are located in
+the same way as for the environment endpoints: the same search path is
+used as for properties or YAML files, but instead of aggregating all
+matching resources, only the first one to match is returned.
After a resource is located, placeholders in the normal format
+(${…}) are resolved using the effective Environment for the
+application name, profile and label supplied. In this way the resource
+endpoint is tightly integrated with the environment
+endpoints. Example, if you have this layout for a GIT (or SVN)
+repository:
application.yml +nginx.conf+
where nginx.conf looks like this:
server {
+ listen 80;
+ server_name ${nginx.server.name};
+}
+and application.yml like this:
nginx:
+ server:
+ name: example.com
+---
+spring:
+ profiles: development
+nginx:
+ server:
+ name: develop.com
+then the /foo/default/master/nginx.conf resource looks like this:
server {
+ listen 80;
+ server_name example.com;
+}
+and /foo/development/master/nginx.conf like this:
server {
+ listen 80;
+ server_name develop.com;
+}
+|
+ Note
+ |
+
+just like the source files for environment configuration, the
+"profile" is used to resolve the file name, so if you want a
+profile-specific file then /*/development/*/logback.xml will be
+resolved by a file called logback-development.xml (in preference
+to logback.xml).
+ |
+
The Config Server runs best as a standalone application, but if you need to you can embed it in another application. Just use the @@ -1915,6 +2096,70 @@ initialize the same way as any other application.
Many 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 spring-cloud-config-monitor library and activate
+the Spring Cloud Bus in your Config Server, then a "/monitor" endpoint
+is enabled.
When the webhook is activated the Config Server will send a
+RefreshRemoteApplicationEvent targeted at the applications it thinks
+might have changed. The change detection can be strategized, but by
+default it just looks for changes in files that match the application
+name (e.g. "foo.properties" is targeted at the "foo" application, and
+"application.properties" is targeted at all applications). The strategy
+if you want to override the behaviour is PropertyPathNotificationExtractor
+which accepts the request headers and body as parameters and returns a list
+of file paths that changed.
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 path={name}. This will
+broadcast to applications matching the "{name}" pattern (can contain
+wildcards).
|
+ Note
+ |
+
+the RefreshRemoteApplicationEvent will only be transmitted if
+the spring-cloud-bus is activated in the Config Server and in the
+client application.
+ |
+
|
+ Note
+ |
++the default configuration also detects filesystem changes in +local git repositories (the webhook is not used in that case but as +soon as you edit a config file a refresh will be broadcast). + | +
If your app wants to be contacted over HTTPS you can set two flags in
+the EurekaInstanceConfig, viz
+eureka.instance.[nonSecurePortEnabled,securePortEnabled]=[false,true]
+respectively. This will make Eureka publish instance information
+showing an explicit preference for secure communication. The Spring
+Cloud DiscoveryClient will always return an https://…; URI for a
+service configured this way, and the Eureka (native) instance
+information will have a secure health check URL. 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.
|
+ Note
+ |
++If your app is running behind a proxy, and the SSL termination +is in the proxy (e.g. if you run in Cloud Foundry or other platforms +as a service) then you will need to ensure that the proxy "forwarded" +headers are intercepted and handled by the application. An embedded +Tomcat container in a Spring Boot app does this automatically if it +has explicit configuration for the 'X-Forwarded-\*` headers. A sign +that you got this wrong will be that the links rendered by your app to +itself will be wrong (the wrong host, port or protocol). + | +
By default, Eureka uses the client heartbeat to determine if a client is up. Unless specified otherwise the Discovery Client will not propagate the -application Spring Boot Actuator current health check status. Which means +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 will not sending +to Eureka. As a consequence every other application won’t be sending traffic to application in state other then 'UP'.
com.netflix.appinfo.HealthCheckHandler.
Cloudfoundry 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). For example:
+Cloudfoundry 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 eureka.instance.instanceId is vcap.application.instance_id. For example:
com.netflix.appinfo.HealthCheckHandler.
eureka:
instance:
hostname: ${vcap.application.uris[0]}
- nonSecurePort: 80
- metadataMap:
- instanceId: ${vcap.application.instance_id:${spring.application.name}:${spring.application.instance_id:${server.port}}}
+ nonSecurePort: 80
By default a eureka instance is registered with an ID that is equal to its host name (i.e. only one service per host). Using Spring Cloud you can override this by providing a unique identifier in eureka.instance.metadataMap.instanceId. For example:
A 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: ${spring.cloud.client.hostname}:${spring.application.name}:${spring.application.instance_id:${server.port}}}. For example myhost:myappname:8080.
Using Spring Cloud you can override this by providing a unique identifier in eureka.instance.instanceId. For example:
eureka:
instance:
- metadataMap:
- instanceId: ${spring.application.name}:${spring.application.instance_id:${random.value}}
+ instanceId: ${spring.application.name}:${spring.application.instance_id:${random.value}}
Once you have an app that is @EnableEurekaClient you can use it to
+
Once you have an app that is @EnableDiscoveryClient (or @EnableEurekaClient) you can use it to
discover service instances from the Eureka Server. One way to do that is to use the native
-com.netflix.discovery.DiscoveryClient (as opposed to the Spring
+com.netflix.discovery.EurekaClient (as opposed to the Spring
Cloud DiscoveryClient), e.g.
@Autowired
-private DiscoveryClient discoveryClient;
+private EurekaClient discoveryClient;
public String serviceUrl() {
InstanceInfo instance = discoveryClient.getNextServerFromEureka("STORES", false);
@@ -2321,7 +2600,7 @@ public String serviceUrl() {
-Don’t use the DiscoveryClient in @PostConstruct method or in a
+
Don’t use the EurekaClient in @PostConstruct method or in a
@Scheduled method (or anywhere where the ApplicationContext might
not be started yet). It is initialized in a SmartLifecycle (with
phase=0) so the earliest you can rely on it being available is in
@@ -2333,9 +2612,9 @@ another SmartLifecycle with higher phase.
-Alternatives to the native Netflix DiscoveryClient
+Alternatives to the native Netflix EurekaClient
-You don’t have to use the raw Netflix DiscoveryClient and usually it
+
You don’t have to use the raw Netflix EurekaClient and usually it
is more convenient to use it behind a wrapper of some sort. Spring
Cloud has support for Feign (a REST client
builder) and also Spring RestTemplate using
@@ -2994,7 +3273,7 @@ public interface StoreClient {
List<Store> getStores();
@RequestMapping(method = RequestMethod.POST, value = "/stores/{storeId}", consumes = "application/json")
- Store update(@PathParameter("storeId") Long storeId, Store store);
+ Store update(@PathVariable("storeId") Long storeId, Store store);
}
@@ -3014,6 +3293,129 @@ in your external configuration (see
above for example).
+Overriding Feign Defaults
+
+A 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 @FeignClient annotation. Spring Cloud creates a new ensemble as an
+ApplicationContext on demand for each named client using FeignClientsConfiguration. This contains (amongst other things) an feign.Decoder, a feign.Encoder, and a feign.Contract.
+
+
+Spring Cloud lets you take full control of the feign client by declaring additional configuration (on top of the FeignClientsConfiguration) using @FeignClient. Example:
+
+
+
+@FeignClient(name = "stores", configuration = FooConfiguration.class)
+public interface StoreClient {
+ //..
+}
+
+
+
+In this case the client is composed from the components already in FeignClientsConfiguration together with any in FooConfiguration (where the latter will override the former).
+
+
+
+
+
+Warning
+
+
+The FooConfiguration has to be @Configuration but take care that it is not in a @ComponentScan for the main application context, otherwise it will be shared by all the @FeignClient`s. If you use `@ComponentScan (or @SpringBootApplication) you need to take steps to avoid it being included (for instance put it in a separate, non-overlapping package, or specify the packages to scan explicitly in the @ComponentScan).
+
+
+
+
+
+
+
+
+Note
+
+
+The serviceId attribute is now deprecated in favor of the name attribute.
+
+
+
+
+
+
+
+
+Warning
+
+
+Previously, using the url attribute, did not require the name attribute. Using name is now required.
+
+
+
+
+
+Spring Cloud Netflix provides the following beans by default for feign (BeanType beanName: ClassName):
+
+
+
+-
+
Decoder feignDecoder: ResponseEntityDecoder (which wraps a SpringDecoder)
+
+-
+
Encoder feignEncoder: SpringEncoder
+
+-
+
Logger feignLogger: Slf4jLogger
+
+-
+
Contract feignContract: SpringMvcContract
+
+
+
+
+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:
+
+
+
+-
+
Logger.Level
+
+-
+
Retryer
+
+-
+
ErrorDecoder
+
+-
+
Request.Options
+
+-
+
Collection<RequestInterceptor>
+
+
+
+
+Creating a bean of one of those type and placing it in a @FeignClient configuration (such as FooConfiguration above) allows you to override each one of the beans described. Example:
+
+
+
+@Configuration
+public class FooConfiguration {
+ @Bean
+ public Contract feignContractg() {
+ return new feign.Contract.Default();
+ }
+
+ @Bean
+ public BasicAuthRequestInterceptor basicAuthRequestInterceptor() {
+ return new BasicAuthRequestInterceptor("user", "password");
+ }
+}
+
+
+
+This replaces the SpringMvcContract with feign.Contract.Default and adds a RequestInterceptor to the collection of RequestInterceptor.
+
+
+Default configurations can be specified in the @EnableFeignClients attribute defaultConfiguration in a similar manner as described above. The difference is that this configuration will apply to all feign clients.
+
+
+
Feign Inheritance Support
Feign supports boilerplate apis via single-inheritance interfaces.
@@ -3043,9 +3445,82 @@ public class UserResource implements UserService {
UserClient.java
-@FeignClient("users")
+package project.user;
+
+@FeignClient("users")
public interface UserClient extends UserService {
+}
+
+
+
+
+Feign request/response compression
+
+You may consider enabling the request or response GZIP compression for your
+Feign requests. You can do this by enabling one of the properties:
+
+
+
+feign.compression.request.enabled=true
+feign.compression.response.enabled=true
+
+
+
+Feign request compression gives you settings similar to what you may set for your web server:
+
+
+
+feign.compression.request.enabled=true
+feign.compression.request.mime-types=text/xml,application/xml,application/json
+feign.compression.request.min-request-size=2048
+
+
+
+These properties allow you to be selective about the compressed media types and minimum request threshold length.
+
+
+
+Feign logging
+
+A 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 DEBUG level.
+
+
+application.yml
+
+logging.level.project.user.UserClient: DEBUG
+
+
+
+The Logger.Level object that you may configure per client, tells Feign how much to log. Choices are:
+
+
+
+-
+
NONE, No logging (DEFAULT).
+
+-
+
BASIC, Log only the request method and URL and the response status code and execution time.
+
+-
+
HEADERS, Log the basic information along with request and response headers.
+
+-
+
FULL, Log the headers, body, and metadata for both requests and responses.
+
+
+
+
+For example, the following would set the Logger.Level to FULL:
+
+
+
+@Configuration
+public class FooConfiguration {
+ @Bean
+ Logger.Level feignLoggerLevel() {
+ return Logger.Level.FULL;
+ }
}
@@ -3073,7 +3548,7 @@ public interface UserClient extends UserService {
-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.
+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.
@@ -3277,7 +3752,7 @@ server if you set a default route ("/"), for example zuul.route.home:
If more fine-grained ignoring is needed, you can specify specific patterns to ignore.
-These patterns are being evaluated at the end of the route location process, which
+These patterns are being 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.
@@ -3285,7 +3760,7 @@ span all services and supersede any other route specification.
application.yml
zuul:
- ignoredPatterns: */admin/**
+ ignoredPatterns: /**/admin/**
routes:
users: /myusers/**
@@ -3296,6 +3771,61 @@ But calls including "/admin/" will not resolve.
+Strangulation Patterns and Local Forwards
+
+A 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
+
+ zuul:
+ routes:
+ first:
+ path: /first/**
+ url: http://first.example.com
+ second:
+ path: /second/**
+ url: forward:/second
+ third:
+ path: /third/**
+ url: forward:/3rd
+ legacy:
+ path: /**
+ url: http://legacy.example.com
+
+
+
+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
+/first/ have been extracted into a new service with an external
+URL. And paths in /second/ are forwared so they can be handled
+locally, e.g. with a normal Spring @RequestMapping. Paths in
+/third/** are also forwarded, but with a different prefix
+(i.e. /third/foo is forwarded to /3rd/foo).
+
+
+
+
+
+Note
+
+
+The ignored pattterns aren’t completely ignored, they just
+aren’t handled by the proxy (so they are also effectively forwarded
+locally).
+
+
+
+
+
+
Uploading Files through Zuul
If you @EnableZuulProxy you can use the proxy paths to
@@ -3586,8 +4116,8 @@ Spring CLI v1.2.3.RELEASE
-$ gvm install springboot 1.2.3.RELEASE
-$ gvm use springboot 1.2.3.RELEASE
+$ gvm install springboot 1.3.0.M5
+$ gvm use springboot 1.3.0.M5
@@ -3596,7 +4126,7 @@ $ gvm use springboot 1.2.3.RELEASE
$ mvn install
-$ spring install org.springframework.cloud:spring-cloud-cli:1.0.2.RELEASE
+$ spring install org.springframework.cloud:spring-cloud-cli:1.1.0.BUILD-SNAPSHOT
@@ -3696,7 +4226,7 @@ AQAjPgt3eFZQXwt8tsHAVv/QHiY5sI2dRcR+...