<commit_before>:github-tag: master
:github-repo: spring-cloud/spring-cloud-netflix
:github-raw: http://raw.github.com/{github-repo}/{github-tag}
:github-code: http://github.com/{github-repo}/tree/{github-tag}
= Spring Cloud Netflix

include::intro.adoc[]

== Service Discovery: Eureka Clients

Service Discovery is one of the key tenets of a microservice based architecture. Trying to hand configure each client or some form of convention can be very difficult to do and can be very brittle.  Eureka is the Netflix Service Discovery Server and Client.  The server can be configured and deployed to be highly available, with each server replicating state about the registered services to the others.

=== Registering with Eureka

When 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:

[source,java,indent=0]
----
@Configuration
@ComponentScan
@EnableAutoConfiguration
@EnableEurekaClient
@RestController
public class Application {

    @RequestMapping("/")
    public String home() {
        return "Hello world";
    }
    
    public static void main(String[] args) {
        new SpringApplicationBuilder(Application.class).web(true).run(args);
    }

}
----

(i.e. utterly normal Spring Boot app). In this example we use
`@EnableEurekaClient` explicitly, but with only Eureka available you
could also use `@EnableDiscoveryClient`. Configuration is required to
locate the Eureka server. Example:


.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 `Environment`, are `${spring.application.name}`,
`${spring.application.name}` and `${server.port}` respectively.

`@EnableEurekaClient` makes the app into both a Eureka "instance"
(i.e. it registers itself) and a "client" (i.e. it can query the
registry to locate other services). The instance behaviour is driven
by `eureka.instance.*` configuration keys, but the defaults will be
fine if you ensure that your application has a
`spring.application.name` (this is the default for the Eureka service
ID, or VIP).

See {github-code}/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/eureka/EurekaInstanceConfigBean.java[EurekaInstanceConfigBean] and {github-code}/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/eureka/EurekaClientConfigBean.java[EurekaClientConfigBean] for more details of the configurable options.

=== Status Page and Health Indicator

The 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. `server.servletPath=/foo`) or management endpoint path
(e.g. `management.contextPath=/admin`). Example:

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

==== 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). By default, the `eureka.instance.instanceId` is `vcap.application.instance_id`. For example:

.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 (https://run.pivotal.io[PWS]).

==== Using Eureka on AWS

If 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 {github-code}/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/eureka/EurekaInstanceConfigBean.java[EurekaInstanceConfigBean] the following way:

[source,java,indent=0]
----
@Bean
@Profile("!default")
public EurekaInstanceConfigBean eurekaInstanceConfig() {
  EurekaInstanceConfigBean b = new EurekaInstanceConfigBean();
  AmazonInfo info = AmazonInfo.Builder.newBuilder().autoBuild("eureka");
  b.setDataCenterInfo(info);
  return b;
}
----

==== Changing the Eureka Instance ID

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

=== Using the EurekaClient

Once you have an app that is `@EnableDiscoveryClient` (or `@EnableEurekaClient`) you can use it to
discover service instances from the <<spring-cloud-eureka-server,
Eureka Server>>. One way to do that is to use the native
`com.netflix.discovery.EurekaClient` (as opposed to the Spring
Cloud `DiscoveryClient`), e.g.

----
@Autowired
private EurekaClient discoveryClient;

public String serviceUrl() {
    InstanceInfo instance = discoveryClient.getNextServerFromEureka("STORES", false);
    return instance.getHomePageUrl();
}
----

[TIP]
====
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
another `SmartLifecycle` with higher phase.
====

=== Alternatives to the native Netflix EurekaClient

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 <<spring-cloud-feign, Feign>> (a REST client
builder) and also <<spring-cloud-ribbon, Spring `RestTemplate`>> using
the logical Eureka service identifiers (VIPs) instead of physical
URLs. To configure Ribbon with a fixed list of physical servers you
can simply set `<client>.ribbon.listOfServers` to a comma-separated
list of physical addresses (or hostnames), where `<client>` is the ID 
of the client.

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 = client.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 `serviceUrl`) with default duration 30 seconds. A
service is not available for discovery by clients until the instance,
the server and the client all have the same metadata in their local
cache (so it could take 3 hearbeats). You can change the period using
`eureka.instance.leaseRenewalIntervalInSeconds` and this will speed up
the process of getting clients connected to other services. In
production it's probably better to stick with the default because
there are some computations internally in the server that make
assumptions about the lease renewal period.

[[spring-cloud-eureka-server]]
== Service Discovery: Eureka Server

Example eureka server (e.g. using spring-cloud-starter-eureka-server to set up the classpath):

[source,java,indent=0]
----
@SpringBootApplication
@EnableEurekaServer
public class Application {

    public static void main(String[] args) {
        new SpringApplicationBuilder(Application.class).web(true).run(args);
    }

}
----

The server has a home page with a UI, and HTTP API endpoints per the
normal Eureka functionality under `/eureka/*`.

Eureka background reading: see https://github.com/cfregly/fluxcapacitor/wiki/NetflixOSS-FAQ#eureka-service-discovery-load-balancer[flux capacitor] and https://groups.google.com/forum/?fromgroups#!topic/eureka_netflix/g3p2r7gHnN0[google group discussion].


[TIP]
====
Due to Gradle's dependency resolution rules and the lack of a parent bom feature, simply depending on spring-cloud-starter-eureka-server can cause failures on application startup. To remedy this the Spring dependency management plugin must be added and the Spring cloud starter parent bom must be imported like so:

.build.gradle
[source,java,indent=0]
----
buildscript {
  dependencies {
    classpath "io.spring.gradle:dependency-management-plugin:0.4.0.RELEASE"
  }
}

apply plugin: "io.spring.dependency-management"

dependencyManagement {
  imports {
    mavenBom 'org.springframework.cloud:spring-cloud-starter-parent:1.0.0.RELEASE'
  }
}
----
====

=== High Availability, Zones and Regions

The Eureka server does not have a backend store, but the service
instances in the registry all have to send heartbeats to keep their
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 <<spring-cloud-ribbon,below for details of Ribbon
support>> on the client side for Zones and Regions.

=== Standalone Mode

The combination of the two caches (client and server) and the
heartbeats make a standalone Eureka server fairly resilient to
failure, as long as there is some sort of monitor or elastic runtime
keeping it alive (e.g. Cloud Foundry). In standalone mode, you might
prefer to switch off the client side behaviour, so it doesn't keep
trying and failing to reach its peers. Example:

.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 `serviceUrl` is pointing to the same host as the local
instance.

=== Peer Awareness

Eureka can be made even more resilient and available by running
multiple instances and asking them to register with each other. In
fact, this is the default behaviour, so all you need to do to make it
work is add a valid `serviceUrl` to a peer, e.g.

.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 `/etc/hosts` to resolve the host names. In
fact, the `eureka.instance.hostname` is not needed if you are running
on a machine that knows its own hostname (it is looked up using
`java.net.InetAddress` by default).

You can add multiple peers to a system, and as long as they are all
connected to each other by at least one edge, they will synchronize
the registrations amongst themselves. If the peers are physically
separated (inside a data centre or between multiple data centres) then
the system can in principle survive split-brain type failures.

=== Prefer IP Address

In some cases, it is preferable for Eureka to advertise the IP Adresses
of services rather than the hostname.  Set `eureka.instance.preferIpAddress`
to `true` and when the application registers with eureka, it will use its
IP Address rather than its hostname.

== Circuit Breaker: Hystrix Clients

Netflix has created a library called https://github.com/Netflix/Hystrix[Hystrix] that implements the http://martinfowler.com/bliki/CircuitBreaker.html[circuit breaker pattern].  In a microservice architecture it is common to have multiple layers of service calls.

.Microservice Graph
image::HystrixGraph.png[]

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.

.Hystrix fallback prevents cascading failures
image::HystrixFallback.png[]

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 `@HystrixCommand` is provided by a Netflix contrib library called
https://github.com/Netflix/Hystrix/tree/master/hystrix-contrib/hystrix-javanica["javanica"].
Spring Cloud automatically wraps Spring beans with that
annotation in a proxy that is connected to the Hystrix circuit
breaker. The circuit breaker calculates when to open and close the
circuit, and what to do in case of a failure.

To configure the `@HystrixCommand` you can use the `commandProperties`
attribute with a list of `@HystrixProperty` annotations.  See
https://github.com/Netflix/Hystrix/tree/master/hystrix-contrib/hystrix-javanica#configuration[here]
for more details.  See the https://github.com/Netflix/Hystrix/wiki/Configuration[Hystrix wiki]
for details on the properties available.

### Propagating the Security Context or using Spring Scopes

If you want some thread local context to propagate into a `@HystrixCommand` the default declaration will not work because it executes the command in a thread pool (in case of timeouts). You can switch Hystrix to use the same thread as the caller using some configuration, or directly in the annotation, by asking it to use a different "Isolation Strategy". For example:

[source,java]
----
@HystrixCommand(fallbackMethod = "stubMyService",
    commandProperties = {
      @HystrixProperty(name="execution.isolation.strategy", value="SEMAPHORE")
    }
) 
...
----

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.

### Health Indicator

The state of the connected circuit breakers are also exposed in the
`/health` endpoint of the calling application. 

[source,json,indent=0]
----
{
    "hystrix": {
        "openCircuitBreakers": [
            "StoreIntegration::getStoresByLocationLink"
        ],
        "status": "CIRCUIT_OPEN"
    },
    "status": "UP"
}
----

=== Hystrix Metrics Stream

To enable the Hystrix metrics stream include a dependency on `spring-boot-starter-actuator`.  This will expose the `/hystrix.stream` as a management endpoint.

[source,xml]
----
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
----

== Circuit Breaker: Hystrix Dashboard

One of the main benefits of Hystrix is the set of metrics it gathers about each HystrixCommand.  The Hystrix Dashboard displays the health of each circuit breaker in an efficient manner.

.Hystrix Dashboard
image::Hystrix.png[]

To run the Hystrix Dashboard annotate your Spring Boot main class with `@EnableHystrixDashboard`.  You then visit `/hystrix` and point the dashboard to an individual instances `/hystrix.stream` endpoint in a Hystrix client application.

=== Turbine

Looking at an individual instances Hystrix data is not very useful in terms of the overall health of the system.  https://github.com/Netflix/Turbine[Turbine] is an application that aggregates all of the relevant `/hystrix.stream` endpoints into a combined `/turbine.stream` for use in the Hystrix Dashboard.  Individual instances are located via Eureka.  Running Turbine is as simple as annotating your main class with the `@EnableTurbine` annotation  (e.g. using spring-cloud-starter-turbine to set up the classpath).  All of the documented configuration properties from https://github.com/Netflix/Turbine/wiki/Configuration-(1.x)[the Turbine 1 wiki] apply.  The only difference is that the `turbine.instanceUrlSuffix` does not need the port prepended as this is handled automatically unless `turbine.instanceInsertPort=false`.

The configuration key `turbine.appConfig` is a list of eureka serviceIds that turbine will use to lookup instances.  The turbine stream is then used in the Hystrix dashboard using a url that looks like: `http://my.turbine.sever:8080/turbine.stream?cluster=<CLUSTERNAME>` (the cluster parameter can be omitted if the name is "default"). The `cluster` parameter must match an entry in `turbine.aggregator.clusterConfig`. Values returned from eureka are uppercase, thus we expect this example to work if there is an app registered with Eureka called "customers":

----
turbine:
  aggregator:
    clusterConfig: CUSTOMERS
  appConfig: customers
----

The `clusterName` can be customized by a SPEL expression in `turbine.clusterNameExpression` with root an instance of `InstanceInfo`. The default value is `appName`, which means that the Eureka serviceId ends up as the cluster key (i.e. the `InstanceInfo` for customers has an `appName` of "CUSTOMERS").  A different example would be `turbine.clusterNameExpression=aSGName`, which would get the cluster name from the AWS ASG name. Another example:

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

----
turbine:
  appConfig: customers,stores
  clusterNameExpression: 'default'
----

Spring Cloud provides a `spring-cloud-starter-turbine` that has all the dependencies you need to get a Turbine server running. Just create a Spring Boot application and annotate it with `@EnableTurbine`.

=== Turbine AMQP

In 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 AMQP messaging. All you need to do on the client is add a dependency to `spring-cloud-netflix-hystrix-amqp` and make sure there is a Rabbit broker available (see Spring Boot documentation for details on how to configure the client credentials, but it should work out of the box for a local broker or in Cloud Foundry).

On the server side Just create a Spring Boot application and annotate it with `@EnableTurbineAmqp` and by default it will come up on port 8989 (point your Hystrix dashboard to that port, any path). You can customize the port using either `server.port` or `turbine.amqp.port`. If you have `spring-boot-starter-web` and `spring-boot-starter-actuator` on the classpath as well, then you can open up the Actuator endpoints on a separate port (with Tomcat by default) by providing a `management.port` which is different.

You can then point the Hystrix Dashboard to the Turbine AMQP Server instead of individual Hystrix streams.  If Turbine AMQP is running on port 8989 on myhost, then put `http://myhost:8989` in the stream input field in the Hystrix Dashboard. Circuits will be prefixed by their respective serviceId, followed by a dot, then the circuit name.

Spring Cloud provides a `spring-cloud-starter-turbine-amqp` that has all the dependencies you need to get a Turbine AMQP server running. You need Java 8 to run the app because it is Netty-based.

== Customizing the AMQP ConnectionFactory

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
`@HystrixConnectionFactory` (on the client) and
`@TurbineConnectionFactory` (on the server) 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.

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 `@*ConnectionFactory` and `@Primary` respectively.

[[spring-cloud-ribbon]]
== Client Side Load Balancer: Ribbon

Ribbon 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 `@FeignClient` then this section also applies.

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 `@FeignClient`
annotation). Spring Cloud creates a new ensemble as an
`ApplicationContext` on demand for each named client using
`RibbonClientConfiguration`. This contains (amongst other things) an
`ILoadBalancer`, a `RestClient`, and a `ServerListFilter`. 

=== Customizing the Ribbon Client

You can configure some bits of a Ribbon client using external
properties in `<client>.ribbon.*`, which is no different than using
the Netflix APIs natively, except that you can use Spring Boot
configuration files. The native options can
be inspected as static fields in `CommonClientConfigKey` (part of
ribbon-core).

Spring Cloud also lets you take full control of the client by
declaring additional configuration (on top of the
`RibbonClientConfiguration`) using `@RibbonClient`. Example:

[source,java,indent=0]
----
@Configuration
@RibbonClient(name = "foo", configuration = FooConfiguration.class)
public class TestConfiguration {
}
----

In this case the client is composed from the components already in
`RibbonClientConfiguration` together with any in `FooConfiguration`
(where the latter generally 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 `@RibbonClients`. 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`).

Spring Cloud Netflix provides the following beans by default for ribbon
(`BeanType` beanName: `ClassName`):

* `IClientConfig` ribbonClientConfig: `DefaultClientConfigImpl`
* `IRule` ribbonRule: `ZoneAvoidanceRule`
* `IPing` ribbonPing: `NoOpPing`
* `ServerList<Server>` ribbonServerList: `ConfigurationBasedServerList`
* `ServerListFilter<Server>` ribbonServerListFilter: `ZonePreferenceServerListFilter`
* `ILoadBalancer` ribbonLoadBalancer: `ZoneAwareLoadBalancer`

Creating a bean of one of those type and placing it in a `@RibbonClient`
configuration (such as `FooConfiguration` above) allows you to override each
one of the beans described.  Example:

[source,java,indent=0]
----
@Configuration
public class FooConfiguration {
    @Bean
    public IPing ribbonPing(IClientConfig config) {
        return new PingUrl();
    }
}
----

This replaces the `NoOpPing` with `PingUrl`.

=== Using Ribbon with Eureka

When Eureka is used in conjunction with Ribbon the `ribbonServerList`
is overridden with an extension of `DiscoveryEnabledNIWSServerList`
which populates the list of servers from Eureka.  It also replaces the
`IPing` interface with `NIWSDiscoveryPing` which delegates to Eureka
to determine if a server is up. The `ServerList` that is installed by
default is a `DomainExtractingServerList` and the purpose of this is
to make physical metadata available to the load balancer without using
AWS AMI metadata (which is what Netflix relies on). By default the
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 `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`).

[[spring-cloud-ribbon-without-eureka]]
=== Example: How to Use Ribbon Without Eureka

Eureka 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 `@RibbonClient` for "stores",
and Eureka is not in use (and not even on the classpath). The Ribbon
client defaults to a configured server list, and you can supply the
configuration like this

.application.yml
----
stores:
  ribbon:
    listOfServers: example.com,google.com
----

=== Example: Disable Eureka use in Ribbon

Setting the property `ribbon.eureka.enabled = false` will explicitly
disable the use of Eureka in Ribbon.

.application.yml
----
ribbon:
  eureka:
   enabled: false
----

=== Using the Ribbon API Directly

You can also use the `LoadBalancerClient` directly. Example:

[source,java,indent=0]
----
public class MyClass {
    @Autowired
    private LoadBalancerClient loadBalancer;

    public void doStuff() {
        ServiceInstance instance = loadBalancer.choose("stores");
        URI storesUri = URI.create(String.format("http://%s:%s", instance.getHost(), instance.getPort()));
        // ... do something with the URI
    }
}
----

[[spring-cloud-feign]]
== Declarative REST Client: Feign

https://github.com/Netflix/feign[Feign] is a declarative web service client.  It makes writing web service clients easier.  To use Feign create an interface and annotate it.  It has pluggable annotation support including Feign annotations and JAX-RS annotations. Feign also supports pluggable encoders and decoders.  Spring Cloud adds support for Spring MVC annotations and for using the same `HttpMessageConverters` used by default in Spring Web.  Spring Cloud integrates Ribbon and Eureka to provide a load balanced http client when using Feign.

Example spring boot app

[source,java,indent=0]
----
@Configuration
@ComponentScan
@EnableAutoConfiguration
@EnableEurekaClient
@EnableFeignClients
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}
----

.StoreClient.java
[source,java,indent=0]
----
@FeignClient("stores")
public interface StoreClient {
    @RequestMapping(method = RequestMethod.GET, value = "/stores")
    List<Store> getStores();

    @RequestMapping(method = RequestMethod.POST, value = "/stores/{storeId}", consumes = "application/json")
    Store update(@PathVariable("storeId") Long storeId, Store store);
}
----

In the `@FeignClient` annotation the String value ("stores" above) is
an arbitrary client name, which is used to create a Ribbon load
balancer (see <<spring-cloud-ribbon,below for details of Ribbon
support>>). You can also specify a URL using the `url` attribute
(absolute value or just a hostname).

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
<<spring-cloud-ribbon-without-eureka,above for example>>).

[[spring-cloud-feign-overriding-defaults]]
=== 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:

[source,java,indent=0]
----
@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`).
<commit_msg>Update spring-cloud-netflix.adoc<commit_after>:github-tag: master
:github-repo: spring-cloud/spring-cloud-netflix
:github-raw: http://raw.github.com/{github-repo}/{github-tag}
:github-code: http://github.com/{github-repo}/tree/{github-tag}
= Spring Cloud Netflix

include::intro.adoc[]

== Service Discovery: Eureka Clients

Service Discovery is one of the key tenets of a microservice based architecture. Trying to hand configure each client or some form of convention can be very difficult to do and can be very brittle.  Eureka is the Netflix Service Discovery Server and Client.  The server can be configured and deployed to be highly available, with each server replicating state about the registered services to the others.

=== Registering with Eureka

When 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:

[source,java,indent=0]
----
@Configuration
@ComponentScan
@EnableAutoConfiguration
@EnableEurekaClient
@RestController
public class Application {

    @RequestMapping("/")
    public String home() {
        return "Hello world";
    }
    
    public static void main(String[] args) {
        new SpringApplicationBuilder(Application.class).web(true).run(args);
    }

}
----

(i.e. utterly normal Spring Boot app). In this example we use
`@EnableEurekaClient` explicitly, but with only Eureka available you
could also use `@EnableDiscoveryClient`. Configuration is required to
locate the Eureka server. Example:


.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 `Environment`, are `${spring.application.name}`,
`${spring.application.name}` and `${server.port}` respectively.

`@EnableEurekaClient` makes the app into both a Eureka "instance"
(i.e. it registers itself) and a "client" (i.e. it can query the
registry to locate other services). The instance behaviour is driven
by `eureka.instance.*` configuration keys, but the defaults will be
fine if you ensure that your application has a
`spring.application.name` (this is the default for the Eureka service
ID, or VIP).

See {github-code}/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/eureka/EurekaInstanceConfigBean.java[EurekaInstanceConfigBean] and {github-code}/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/eureka/EurekaClientConfigBean.java[EurekaClientConfigBean] for more details of the configurable options.

=== Status Page and Health Indicator

The 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. `server.servletPath=/foo`) or management endpoint path
(e.g. `management.contextPath=/admin`). Example:

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

==== 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). By default, the `eureka.instance.instanceId` is `vcap.application.instance_id`. For example:

.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 (https://run.pivotal.io[PWS]).

==== Using Eureka on AWS

If 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 {github-code}/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/eureka/EurekaInstanceConfigBean.java[EurekaInstanceConfigBean] the following way:

[source,java,indent=0]
----
@Bean
@Profile("!default")
public EurekaInstanceConfigBean eurekaInstanceConfig() {
  EurekaInstanceConfigBean b = new EurekaInstanceConfigBean();
  AmazonInfo info = AmazonInfo.Builder.newBuilder().autoBuild("eureka");
  b.setDataCenterInfo(info);
  return b;
}
----

==== Changing the Eureka Instance ID

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

=== Using the EurekaClient

Once you have an app that is `@EnableDiscoveryClient` (or `@EnableEurekaClient`) you can use it to
discover service instances from the <<spring-cloud-eureka-server,
Eureka Server>>. One way to do that is to use the native
`com.netflix.discovery.EurekaClient` (as opposed to the Spring
Cloud `DiscoveryClient`), e.g.

----
@Autowired
private EurekaClient discoveryClient;

public String serviceUrl() {
    InstanceInfo instance = discoveryClient.getNextServerFromEureka("STORES", false);
    return instance.getHomePageUrl();
}
----

[TIP]
====
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
another `SmartLifecycle` with higher phase.
====

=== Alternatives to the native Netflix EurekaClient

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 <<spring-cloud-feign, Feign>> (a REST client
builder) and also <<spring-cloud-ribbon, Spring `RestTemplate`>> using
the logical Eureka service identifiers (VIPs) instead of physical
URLs. To configure Ribbon with a fixed list of physical servers you
can simply set `<client>.ribbon.listOfServers` to a comma-separated
list of physical addresses (or hostnames), where `<client>` is the ID 
of the client.

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 = client.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 `serviceUrl`) with default duration 30 seconds. A
service is not available for discovery by clients until the instance,
the server and the client all have the same metadata in their local
cache (so it could take 3 hearbeats). You can change the period using
`eureka.instance.leaseRenewalIntervalInSeconds` and this will speed up
the process of getting clients connected to other services. In
production it's probably better to stick with the default because
there are some computations internally in the server that make
assumptions about the lease renewal period.

[[spring-cloud-eureka-server]]
== Service Discovery: Eureka Server

Example eureka server (e.g. using spring-cloud-starter-eureka-server to set up the classpath):

[source,java,indent=0]
----
@SpringBootApplication
@EnableEurekaServer
public class Application {

    public static void main(String[] args) {
        new SpringApplicationBuilder(Application.class).web(true).run(args);
    }

}
----

The server has a home page with a UI, and HTTP API endpoints per the
normal Eureka functionality under `/eureka/*`.

Eureka background reading: see https://github.com/cfregly/fluxcapacitor/wiki/NetflixOSS-FAQ#eureka-service-discovery-load-balancer[flux capacitor] and https://groups.google.com/forum/?fromgroups#!topic/eureka_netflix/g3p2r7gHnN0[google group discussion].


[TIP]
====
Due to Gradle's dependency resolution rules and the lack of a parent bom feature, simply depending on spring-cloud-starter-eureka-server can cause failures on application startup. To remedy this the Spring dependency management plugin must be added and the Spring cloud starter parent bom must be imported like so:

.build.gradle
[source,java,indent=0]
----
buildscript {
  dependencies {
    classpath "io.spring.gradle:dependency-management-plugin:0.4.0.RELEASE"
  }
}

apply plugin: "io.spring.dependency-management"

dependencyManagement {
  imports {
    mavenBom 'org.springframework.cloud:spring-cloud-starter-parent:1.0.0.RELEASE'
  }
}
----
====

=== High Availability, Zones and Regions

The Eureka server does not have a backend store, but the service
instances in the registry all have to send heartbeats to keep their
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 <<spring-cloud-ribbon,below for details of Ribbon
support>> on the client side for Zones and Regions.

=== Standalone Mode

The combination of the two caches (client and server) and the
heartbeats make a standalone Eureka server fairly resilient to
failure, as long as there is some sort of monitor or elastic runtime
keeping it alive (e.g. Cloud Foundry). In standalone mode, you might
prefer to switch off the client side behaviour, so it doesn't keep
trying and failing to reach its peers. Example:

.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 `serviceUrl` is pointing to the same host as the local
instance.

=== Peer Awareness

Eureka can be made even more resilient and available by running
multiple instances and asking them to register with each other. In
fact, this is the default behaviour, so all you need to do to make it
work is add a valid `serviceUrl` to a peer, e.g.

.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 `/etc/hosts` to resolve the host names. In
fact, the `eureka.instance.hostname` is not needed if you are running
on a machine that knows its own hostname (it is looked up using
`java.net.InetAddress` by default).

You can add multiple peers to a system, and as long as they are all
connected to each other by at least one edge, they will synchronize
the registrations amongst themselves. If the peers are physically
separated (inside a data centre or between multiple data centres) then
the system can in principle survive split-brain type failures.

=== Prefer IP Address

In some cases, it is preferable for Eureka to advertise the IP Adresses
of services rather than the hostname.  Set `eureka.instance.preferIpAddress`
to `true` and when the application registers with eureka, it will use its
IP Address rather than its hostname.

== Circuit Breaker: Hystrix Clients

Netflix has created a library called https://github.com/Netflix/Hystrix[Hystrix] that implements the http://martinfowler.com/bliki/CircuitBreaker.html[circuit breaker pattern].  In a microservice architecture it is common to have multiple layers of service calls.

.Microservice Graph
image::HystrixGraph.png[]

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.

.Hystrix fallback prevents cascading failures
image::HystrixFallback.png[]

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 `@HystrixCommand` is provided by a Netflix contrib library called
https://github.com/Netflix/Hystrix/tree/master/hystrix-contrib/hystrix-javanica["javanica"].
Spring Cloud automatically wraps Spring beans with that
annotation in a proxy that is connected to the Hystrix circuit
breaker. The circuit breaker calculates when to open and close the
circuit, and what to do in case of a failure.

To configure the `@HystrixCommand` you can use the `commandProperties`
attribute with a list of `@HystrixProperty` annotations.  See
https://github.com/Netflix/Hystrix/tree/master/hystrix-contrib/hystrix-javanica#configuration[here]
for more details.  See the https://github.com/Netflix/Hystrix/wiki/Configuration[Hystrix wiki]
for details on the properties available.

### Propagating the Security Context or using Spring Scopes

If you want some thread local context to propagate into a `@HystrixCommand` the default declaration will not work because it executes the command in a thread pool (in case of timeouts). You can switch Hystrix to use the same thread as the caller using some configuration, or directly in the annotation, by asking it to use a different "Isolation Strategy". For example:

[source,java]
----
@HystrixCommand(fallbackMethod = "stubMyService",
    commandProperties = {
      @HystrixProperty(name="execution.isolation.strategy", value="SEMAPHORE")
    }
) 
...
----

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.

### Health Indicator

The state of the connected circuit breakers are also exposed in the
`/health` endpoint of the calling application. 

[source,json,indent=0]
----
{
    "hystrix": {
        "openCircuitBreakers": [
            "StoreIntegration::getStoresByLocationLink"
        ],
        "status": "CIRCUIT_OPEN"
    },
    "status": "UP"
}
----

=== Hystrix Metrics Stream

To enable the Hystrix metrics stream include a dependency on `spring-boot-starter-actuator`.  This will expose the `/hystrix.stream` as a management endpoint.

[source,xml]
----
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
----

== Circuit Breaker: Hystrix Dashboard

One of the main benefits of Hystrix is the set of metrics it gathers about each HystrixCommand.  The Hystrix Dashboard displays the health of each circuit breaker in an efficient manner.

.Hystrix Dashboard
image::Hystrix.png[]

To run the Hystrix Dashboard annotate your Spring Boot main class with `@EnableHystrixDashboard`.  You then visit `/hystrix` and point the dashboard to an individual instances `/hystrix.stream` endpoint in a Hystrix client application.

=== Turbine

Looking at an individual instances Hystrix data is not very useful in terms of the overall health of the system.  https://github.com/Netflix/Turbine[Turbine] is an application that aggregates all of the relevant `/hystrix.stream` endpoints into a combined `/turbine.stream` for use in the Hystrix Dashboard.  Individual instances are located via Eureka.  Running Turbine is as simple as annotating your main class with the `@EnableTurbine` annotation  (e.g. using spring-cloud-starter-turbine to set up the classpath).  All of the documented configuration properties from https://github.com/Netflix/Turbine/wiki/Configuration-(1.x)[the Turbine 1 wiki] apply.  The only difference is that the `turbine.instanceUrlSuffix` does not need the port prepended as this is handled automatically unless `turbine.instanceInsertPort=false`.

The configuration key `turbine.appConfig` is a list of eureka serviceIds that turbine will use to lookup instances.  The turbine stream is then used in the Hystrix dashboard using a url that looks like: `http://my.turbine.sever:8080/turbine.stream?cluster=<CLUSTERNAME>` (the cluster parameter can be omitted if the name is "default"). The `cluster` parameter must match an entry in `turbine.aggregator.clusterConfig`. Values returned from eureka are uppercase, thus we expect this example to work if there is an app registered with Eureka called "customers":

----
turbine:
  aggregator:
    clusterConfig: CUSTOMERS
  appConfig: customers
----

The `clusterName` can be customized by a SPEL expression in `turbine.clusterNameExpression` with root an instance of `InstanceInfo`. The default value is `appName`, which means that the Eureka serviceId ends up as the cluster key (i.e. the `InstanceInfo` for customers has an `appName` of "CUSTOMERS").  A different example would be `turbine.clusterNameExpression=aSGName`, which would get the cluster name from the AWS ASG name. Another example:

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

----
turbine:
  appConfig: customers,stores
  clusterNameExpression: 'default'
----

Spring Cloud provides a `spring-cloud-starter-turbine` that has all the dependencies you need to get a Turbine server running. Just create a Spring Boot application and annotate it with `@EnableTurbine`.

=== Turbine AMQP

In 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 AMQP messaging. All you need to do on the client is add a dependency to `spring-cloud-netflix-hystrix-amqp` and make sure there is a Rabbit broker available (see Spring Boot documentation for details on how to configure the client credentials, but it should work out of the box for a local broker or in Cloud Foundry).

On the server side Just create a Spring Boot application and annotate it with `@EnableTurbineAmqp` and by default it will come up on port 8989 (point your Hystrix dashboard to that port, any path). You can customize the port using either `server.port` or `turbine.amqp.port`. If you have `spring-boot-starter-web` and `spring-boot-starter-actuator` on the classpath as well, then you can open up the Actuator endpoints on a separate port (with Tomcat by default) by providing a `management.port` which is different.

You can then point the Hystrix Dashboard to the Turbine AMQP Server instead of individual Hystrix streams.  If Turbine AMQP is running on port 8989 on myhost, then put `http://myhost:8989` in the stream input field in the Hystrix Dashboard. Circuits will be prefixed by their respective serviceId, followed by a dot, then the circuit name.

Spring Cloud provides a `spring-cloud-starter-turbine-amqp` that has all the dependencies you need to get a Turbine AMQP server running. You need Java 8 to run the app because it is Netty-based.

== Customizing the AMQP ConnectionFactory

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
`@HystrixConnectionFactory` (on the client) and
`@TurbineConnectionFactory` (on the server) 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.

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 `@*ConnectionFactory` and `@Primary` respectively.

[[spring-cloud-ribbon]]
== Client Side Load Balancer: Ribbon

Ribbon 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 `@FeignClient` then this section also applies.

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 `@FeignClient`
annotation). Spring Cloud creates a new ensemble as an
`ApplicationContext` on demand for each named client using
`RibbonClientConfiguration`. This contains (amongst other things) an
`ILoadBalancer`, a `RestClient`, and a `ServerListFilter`. 

=== Customizing the Ribbon Client

You can configure some bits of a Ribbon client using external
properties in `<client>.ribbon.*`, which is no different than using
the Netflix APIs natively, except that you can use Spring Boot
configuration files. The native options can
be inspected as static fields in `CommonClientConfigKey` (part of
ribbon-core).

Spring Cloud also lets you take full control of the client by
declaring additional configuration (on top of the
`RibbonClientConfiguration`) using `@RibbonClient`. Example:

[source,java,indent=0]
----
@Configuration
@RibbonClient(name = "foo", configuration = FooConfiguration.class)
public class TestConfiguration {
}
----

In this case the client is composed from the components already in
`RibbonClientConfiguration` together with any in `FooConfiguration`
(where the latter generally 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 `@RibbonClients`. 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`).

Spring Cloud Netflix provides the following beans by default for ribbon
(`BeanType` beanName: `ClassName`):

* `IClientConfig` ribbonClientConfig: `DefaultClientConfigImpl`
* `IRule` ribbonRule: `ZoneAvoidanceRule`
* `IPing` ribbonPing: `NoOpPing`
* `ServerList<Server>` ribbonServerList: `ConfigurationBasedServerList`
* `ServerListFilter<Server>` ribbonServerListFilter: `ZonePreferenceServerListFilter`
* `ILoadBalancer` ribbonLoadBalancer: `ZoneAwareLoadBalancer`

Creating a bean of one of those type and placing it in a `@RibbonClient`
configuration (such as `FooConfiguration` above) allows you to override each
one of the beans described.  Example:

[source,java,indent=0]
----
@Configuration
public class FooConfiguration {
    @Bean
    public IPing ribbonPing(IClientConfig config) {
        return new PingUrl();
    }
}
----

This replaces the `NoOpPing` with `PingUrl`.

=== Using Ribbon with Eureka

When Eureka is used in conjunction with Ribbon the `ribbonServerList`
is overridden with an extension of `DiscoveryEnabledNIWSServerList`
which populates the list of servers from Eureka.  It also replaces the
`IPing` interface with `NIWSDiscoveryPing` which delegates to Eureka
to determine if a server is up. The `ServerList` that is installed by
default is a `DomainExtractingServerList` and the purpose of this is
to make physical metadata available to the load balancer without using
AWS AMI metadata (which is what Netflix relies on). By default the
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 `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`).

[[spring-cloud-ribbon-without-eureka]]
=== Example: How to Use Ribbon Without Eureka

Eureka 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 `@RibbonClient` for "stores",
and Eureka is not in use (and not even on the classpath). The Ribbon
client defaults to a configured server list, and you can supply the
configuration like this

.application.yml
----
stores:
  ribbon:
    listOfServers: example.com,google.com
----

=== Example: Disable Eureka use in Ribbon

Setting the property `ribbon.eureka.enabled = false` will explicitly
disable the use of Eureka in Ribbon.

.application.yml
----
ribbon:
  eureka:
   enabled: false
----

=== Using the Ribbon API Directly

You can also use the `LoadBalancerClient` directly. Example:

[source,java,indent=0]
----
public class MyClass {
    @Autowired
    private LoadBalancerClient loadBalancer;

    public void doStuff() {
        ServiceInstance instance = loadBalancer.choose("stores");
        URI storesUri = URI.create(String.format("http://%s:%s", instance.getHost(), instance.getPort()));
        // ... do something with the URI
    }
}
----

[[spring-cloud-feign]]
== Declarative REST Client: Feign

https://github.com/Netflix/feign[Feign] is a declarative web service client.  It makes writing web service clients easier.  To use Feign create an interface and annotate it.  It has pluggable annotation support including Feign annotations and JAX-RS annotations. Feign also supports pluggable encoders and decoders.  Spring Cloud adds support for Spring MVC annotations and for using the same `HttpMessageConverters` used by default in Spring Web.  Spring Cloud integrates Ribbon and Eureka to provide a load balanced http client when using Feign.

Example spring boot app

[source,java,indent=0]
----
@Configuration
@ComponentScan
@EnableAutoConfiguration
@EnableEurekaClient
@EnableFeignClients
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}
----

.StoreClient.java
[source,java,indent=0]
----
@FeignClient("stores")
public interface StoreClient {
    @RequestMapping(method = RequestMethod.GET, value = "/stores")
    List<Store> getStores();

    @RequestMapping(method = RequestMethod.POST, value = "/stores/{storeId}", consumes = "application/json")
    Store update(@PathVariable("storeId") Long storeId, Store store);
}
----

In the `@FeignClient` annotation the String value ("stores" above) is
an arbitrary client name, which is used to create a Ribbon load
balancer (see <<spring-cloud-ribbon,below for details of Ribbon
support>>). You can also specify a URL using the `url` attribute
(absolute value or just a hostname).

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
<<spring-cloud-ribbon-without-eureka,above for example>>).

[[spring-cloud-feign-overriding-defaults]]
=== 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:

[source,java,indent=0]
----
@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`).

{'fraction_non_alphanumeric': 0.0723833759846741, 'fraction_numerical': 0.0022016669764250074, 'mean_word_length': 4.527738264580369, 'pattern_counts': {'":': 10, '<': 59, '<?xml version=': 0, '>': 61, 'https://': 22, 'lorem ipsum': 0, 'www.': 0, 'xml': 2}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7143066', 'n_tokens_mistral': 19137, 'n_tokens_neox': 18545, 'n_words': 9000}