diff --git a/spring-cloud.html b/spring-cloud.html index 61133cb..7a7be39 100644 --- a/spring-cloud.html +++ b/spring-cloud.html @@ -455,9 +455,11 @@ body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-b
  • Key Management
  • Creating a Key Store for Testing
  • Using Multiple Keys and Key Rotation
  • -
  • Embedding the Config Server
  • +
  • Serving Plain Text
  • +
  • Embedding the Config Server
  • +
  • Push Notifications and Spring Cloud Bus
  • Spring Cloud Config Client
  • -
  • Declarative REST Client: Feign
  • +
  • Declarative REST Client: Feign + +
  • External Configuration: Archaius
  • Router and Filter: Zuul
  • Spring Boot Cloud CLI @@ -754,8 +767,8 @@ things with their parent.

    Changing the Location of Bootstrap Properties

    -

    The bootstrap.yml (or .properties) location can be specified using -`spring.cloud.bootstrap.name (default "bootstrap") or +

    The bootstrap.yml (or .properties) location can be specified using +spring.cloud.bootstrap.name (default "bootstrap") or spring.cloud.bootstrap.location (default empty), e.g. in System properties. Those properties behave like the spring.config.* variants with the same name, in fact they are used to set up the @@ -1057,12 +1070,7 @@ the provided `@LoadBalanced Qualifier:

    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.

    -
    - +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.
    @@ -1078,9 +1086,9 @@ $ mvn spring-boot:run
    -

    The server is a Spring Boot application so you can build the jar file -and run that (java -jar …​) or pull it down from a Maven -repository. Then try it out as a client:

    +

    The server is a Spring Boot application so you can run it from your +IDE instead if you prefer (the main class is +ConfigServerApplication). Then try it out a client:

    @@ -1272,7 +1280,78 @@ the config server URL.

    The Server provides an HTTP, resource-based API for external configuration (name-value pairs, or equivalent YAML content). The server is easily embeddable in a Spring Boot application using the -@EnableConfigServer annotation.

    +@EnableConfigServer annotation. So this app is a config server:

    +
    +
    +
    ConfigServer.java
    +
    +
    @SpringBootApplication
    +@EnableConfigServer
    +public class ConfigServer {
    +  public static void main(String[] args) {
    +    SpringApplication.run(ConfigServer.class, args);
    +  }
    +}
    +
    +
    +
    +

    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 spring.config.name=configserver (there +is a configserver.yml in the Config Server jar). Another is +to use your own application.properties, e.g.

    +
    +
    +
    application.properties
    +
    +
    server.port: 8888
    +spring.cloud.config.server.git.uri: file://${user.home}/config-repo
    +
    +
    +
    +

    where ${user.home}/config-repo is a git repository containing +YAML and properties files.

    +
    +
    + + + + + +
    +
    Tip
    +
    +
    +

    Here’s a recipe for creating the git repository in the example +above:

    +
    +
    +
    +
    $ cd $HOME
    +$ mkdir config-repo
    +$ cd config-repo
    +$ git init .
    +$ echo info.foo: bar > application.properties
    +$ git add -A .
    +$ git commit -m "Add application.properties"
    +
    +
    +
    +
    +
    + + + + + +
    +
    Warning
    +
    +using the local filesystem for your git repository is +intended for testing only. Use a server to host your +configuration repositories in production. +

    Environment Repository

    @@ -1366,7 +1445,10 @@ them from the shell with quotes '').

    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:

    @@ -1377,22 +1459,83 @@ repositories:

    git: uri: https://github.com/spring-cloud-samples/config-repo repos: - simple: https://github.com/pattern1/config-repo + simple: https://github.com/simple/config-repo special: - pattern: pattern*,*pattern1* - uri: https://github.com/pattern2/config-repo + pattern: special*/dev*,*special*/dev* + uri: https://github.com/special/config-repo local: pattern: local* uri: file:/home/configsvc/config-repo
    -

    In the above example, if {application} does not match to 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). The -pattern format is a comma-separated list of application names with -wildcards.

    +

    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).

    +
    +
    + + + + + +
    +
    Note
    +
    +the "one-liner" short cut used in the "simple" example above can +only be used if the only property to be set is the URI. If you need to +set anything else (credentials, pattern, etc.) you need to use the full +form. +
    +
    +
    +

    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 @@ -1613,6 +1756,16 @@ instance:

    +

    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.

    @@ -1638,10 +1791,25 @@ configured with a symmetric key or a full key pair):

    mysecret
    +
    + + + + + +
    +
    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 encypted value and add the {cipher} prefix before you put +

    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 -to a remote, potentially insecure store. The /encypt and /decrypt +to a remote, potentially insecure store. The /encrypt and /decrypt endpoints also both accept paths of the form /*/{name}/{profiles} which can be used to control cryptography per application (name) and profile when clients call into the main Environment resource.

    @@ -1674,7 +1842,7 @@ mysecret
    -

    To use a key in a file (e.g. an RSA public key for encyption) prepend +

    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.

    @@ -1810,8 +1978,108 @@ handle all encryption as well as decryption.
    -
    -

    Embedding the Config Server

    +
    + +
    +

    Serving Plain Text

    +
    +
    +

    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). +
    +
    +
    +
    +
    +

    Embedding the Config Server

    +

    The Config Server runs best as a standalone application, but if you need to you can embed it in another application. Just use the @@ -1829,6 +2097,70 @@ initialize the same way as any other application.

    +
    +

    Push Notifications and Spring Cloud Bus

    +
    +
    +

    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). +
    +
    +

    Spring Cloud Config Client

    @@ -2106,17 +2438,77 @@ non-default context path or servlet path
    eureka:
       instance:
    -    statusPageUrlPath: ${management.contextPath}/info
    -    healthCheckUrlPath: ${management.contextPath}/health
    + statusPageUrlPath: ${management.context-path}/info + healthCheckUrlPath: ${management.context-path}/health
    -

    These links show up in the metadata that is consumers by clients, and +

    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 Application

    +
    +

    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). +
    +
    +
    +
    +

    Eureka’s Health Checks

    +
    +

    By 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 com.netflix.appinfo.HealthCheckHandler.

    +
    +
    +

    Eureka Metadata for Instances and Clients

    It’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 eureka.instance.metadataMap, and this will be accessible in the remote clients, but in general will not change the behaviour of the client, unless it is made aware of the meaning of the metadata. There are a couple of special cases described below where Spring Cloud already assigns meaning to the metadata map.

    @@ -2124,7 +2516,7 @@ application, so it’s helpful if they are accurate.

    Using Eureka on Cloudfoundry

    -

    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:

    application.yml
    @@ -2132,9 +2524,7 @@ application, so it’s helpful if they are accurate.

    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
    @@ -2160,17 +2550,19 @@ public EurekaInstanceConfigBean eurekaInstanceConfig() {
    -

    Making the Eureka Instance ID Unique

    +

    Changing the Eureka Instance ID

    -

    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:

    application.yml
    eureka:
       instance:
    -    metadataMap:
    -      instanceId: ${spring.application.name}:${spring.application.instance_id:${random.value}}
    + instanceId: ${spring.application.name}:${spring.application.instance_id:${random.value}}
    @@ -2183,17 +2575,17 @@ random value will not be needed.

    -

    Using the DiscoveryClient

    +

    Using the EurekaClient

    -

    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);
    @@ -2209,7 +2601,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 @@ -2221,9 +2613,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 @@ -2526,9 +2918,6 @@ for details on the properties available.

    The same thing applies if you are using @SessionScope or @RequestScope. You will know when you need to do this because of a runtime exception that says it can’t find the scoped context.

    -
    -

    In particular you might be interested

    -

    Health Indicator

    @@ -2743,7 +3132,7 @@ explicitly in the @ComponentScan).

    IPing ribbonPing: NoOpPing

  • -

    ServerList<Server> ribbonServerList: `ConfigurationBasedServerList

    +

    ServerList<Server> ribbonServerList: ConfigurationBasedServerList

  • ServerListFilter<Server> ribbonServerListFilter: ZonePreferenceServerListFilter

    @@ -2788,7 +3177,7 @@ server list will be constructed with "zone" information as provided in the instance metadata (so on the client set eureka.instance.metadataMap.zone), and if that is missing it can use the domain name from the server hostname as a proxy for zone (if the -flag approximateZoneFromDomain is set). Once the zone information is +flag approximateZoneFromHostname is set). Once the zone information is available it can be used in a ServerListFilter (by default it will be used to locate a server in the same zone as the client because the default is a ZonePreferenceServerListFilter).

    @@ -2885,7 +3274,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); } @@ -2904,6 +3293,250 @@ don’t want to use Eureka, you can simply configure a list of servers 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 used for every @FeignClient. 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. +
    +
    +
    +

    Placeholders are supported in the name and url attributes.

    +
    +
    +
    +
    @FeignClient(name = "${feign.name}", url = "${feign.url}")
    +public interface StoreClient {
    +    //..
    +}
    +
    +
    +
    +

    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. +This allows grouping common operations into convenient base interfaces. +Together with Spring MVC you can share the same contract for your +REST endpoint and Feign client.

    +
    +
    +
    UserService.java
    +
    +
    public interface UserService {
    +
    +    @RequestMapping(method = RequestMethod.GET, value ="/users/{id}")
    +    User getUser(@PathVariable("id") long id);
    +}
    +
    +
    +
    +
    UserResource.java
    +
    +
    @RestController
    +public class UserResource implements UserService {
    +
    +}
    +
    +
    +
    +
    UserClient.java
    +
    +
    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;
    +    }
    +}
    +
    +
    +
    @@ -2927,7 +3560,7 @@ in your external configuration (see
    -

    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.

    @@ -3007,7 +3640,7 @@ configured routes map, then it will be unignored. Example:

    application.yml
     zuul:
    -  ignoredServices: *
    +  ignoredServices: '*'
       routes:
         users: /myusers/**
    @@ -3118,7 +3751,7 @@ Set that flag to "true" to have the Ribbon client automatically retry failed req the Ribbon client configuration).

    -

    The X-Forwarded-Host header added to the forwarded requests by +

    The X-Forwarded-Host header is added to the forwarded requests by default. To turn it off set zuul.addProxyHeaders = false. The prefix path is stripped by default, and the request to the backend picks up a header "X-Forwarded-Prefix" ("/myusers" in the examples @@ -3129,6 +3762,80 @@ above).

    server if you set a default route ("/"), for example zuul.route.home: / would route all traffic (i.e. "/**") to the "home" service.

    +
    +

    If more fine-grained ignoring is needed, you can specify specific patterns to ignore. +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.

    +
    +
    +
    application.yml
    +
    +
     zuul:
    +  ignoredPatterns: /**/admin/**
    +  routes:
    +    users: /myusers/**
    +
    +
    +
    +

    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.

    +
    + +
    +

    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

    @@ -3369,21 +4076,98 @@ info:
    -

    Customizing the AMQP ConnectionFactory

    +

    Customizing the Message Broker

    -

    If you are using AMQP there needs to be a ConnectionFactory (from -Spring Rabbit) in the application context. If there is a single -ConnectionFactory it will be used, or if there is a one qualified as -@BusConnectionFactory it will be preferred over others, otherwise -the @Primary one will be used. If there are multiple unqualified -connection factories there will be an error.

    +

    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, Kafka and Redis +(spring-cloud-starter-bus-[amqp,kafka,redis]). 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.

    -

    Note that Spring Boot (as of 1.2.2) creates a ConnectionFactory that -is not @Primary, so if you want to use one connection factory for -the bus and another for business messages, you need to create both, -and annotate them @BusConnectionFactory and @Primary respectively.

    +

    To lean more about how to customize the message broker settings +consult the Spring Cloud Stream documentation.

    +
    +
    +
    +
    +

    Tracing Bus Events

    +
    +
    +

    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 AckRemoteAppplicationEvent 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. +
    @@ -3421,8 +4205,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
    @@ -3431,7 +4215,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
    @@ -3531,7 +4315,7 @@ AQAjPgt3eFZQXwt8tsHAVv/QHiY5sI2dRcR+...