Files
spring-cloud-static/spring-cloud-netflix/2.0.0.M5/spring-cloud-netflix.xml
2017-12-02 02:57:40 +00:00

2627 lines
150 KiB
XML

<?xml version="1.0" encoding="UTF-8"?>
<?asciidoc-toc?>
<?asciidoc-numbered?>
<book xmlns="http://docbook.org/ns/docbook" xmlns:xl="http://www.w3.org/1999/xlink" version="5.0" xml:lang="en">
<info>
<title>Spring Cloud Netflix</title>
<date>2017-12-02</date>
</info>
<preface>
<title></title>
<simpara><emphasis role="strong">2.0.0.M5</emphasis></simpara>
<simpara>This project provides Netflix OSS integrations for Spring Boot apps through autoconfiguration
and binding to the Spring Environment and other Spring programming model idioms. With a few
simple annotations you can quickly enable and configure the common patterns inside your
application and build large distributed systems with battle-tested Netflix components. The
patterns provided include Service Discovery (Eureka), Circuit Breaker (Hystrix),
Intelligent Routing (Zuul) and Client Side Load Balancing (Ribbon).</simpara>
</preface>
<chapter xml:id="_service_discovery_eureka_clients">
<title>Service Discovery: Eureka Clients</title>
<simpara>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.</simpara>
<section xml:id="netflix-eureka-client-starter">
<title>How to Include Eureka Client</title>
<simpara>To include Eureka Client in your project use the starter with group <literal>org.springframework.cloud</literal>
and artifact id <literal>spring-cloud-starter-netflix-eureka-client</literal>. See the <link xl:href="http://projects.spring.io/spring-cloud/">Spring Cloud Project page</link>
for details on setting up your build system with the current Spring Cloud Release Train.</simpara>
</section>
<section xml:id="_registering_with_eureka">
<title>Registering with Eureka</title>
<simpara>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.</simpara>
<simpara>Example eureka client:</simpara>
<programlisting language="java" linenumbering="unnumbered">@SpringBootApplication
@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);
}
}</programlisting>
<simpara>(i.e. utterly normal Spring Boot app). By having <literal>spring-cloud-starter-netflix-eureka-client</literal>
on the classpath your application will automatically register with the Eureka Server. Configuration is required to
locate the Eureka server. Example:</simpara>
<formalpara>
<title>application.yml</title>
<para>
<screen>eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/</screen>
</para>
</formalpara>
<simpara>where "defaultZone" is a magic string fallback value that provides the
service URL for any client that doesn&#8217;t express a preference
(i.e. it&#8217;s a useful default).</simpara>
<simpara>The default application name (service ID), virtual host and non-secure
port, taken from the <literal>Environment</literal>, are <literal>${spring.application.name}</literal>,
<literal>${spring.application.name}</literal> and <literal>${server.port}</literal> respectively.</simpara>
<simpara>Having <literal>spring-cloud-starter-netflix-eureka-client</literal> on the classpath
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 <literal>eureka.instance.*</literal> configuration keys, but the defaults will be
fine if you ensure that your application has a
<literal>spring.application.name</literal> (this is the default for the Eureka service
ID, or VIP).</simpara>
<simpara>See <link xl:href="http://github.com/spring-cloud/spring-cloud-netflix/tree/master/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaInstanceConfigBean.java">EurekaInstanceConfigBean</link> and <link xl:href="http://github.com/spring-cloud/spring-cloud-netflix/tree/master/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaClientConfigBean.java">EurekaClientConfigBean</link> for more details of the configurable options.</simpara>
<simpara>To disable the Eureka Discovery Client you can set <literal>eureka.client.enabled</literal> to <literal>false</literal>.</simpara>
</section>
<section xml:id="_authenticating_with_the_eureka_server">
<title>Authenticating with the Eureka Server</title>
<simpara>HTTP basic authentication will be automatically added to your eureka
client if one of the <literal>eureka.client.serviceUrl.defaultZone</literal> URLs has
credentials embedded in it (curl style, like
<literal><link xl:href="http://user:password@localhost:8761/eureka">http://user:password@localhost:8761/eureka</link></literal>). For more complex needs
you can create a <literal>@Bean</literal> of type <literal>DiscoveryClientOptionalArgs</literal> and
inject <literal>ClientFilter</literal> instances into it, all of which will be applied
to the calls from the client to the server.</simpara>
<note>
<simpara>Because of a limitation in Eureka it isn&#8217;t possible to support
per-server basic auth credentials, so only the first set that are
found will be used.</simpara>
</note>
</section>
<section xml:id="_status_page_and_health_indicator">
<title>Status Page and Health Indicator</title>
<simpara>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. <literal>server.servletPath=/foo</literal>) or management endpoint path
(e.g. <literal>management.contextPath=/admin</literal>). Example:</simpara>
<formalpara>
<title>application.yml</title>
<para>
<screen>eureka:
instance:
statusPageUrlPath: ${management.context-path}/info
healthCheckUrlPath: ${management.context-path}/health</screen>
</para>
</formalpara>
<simpara>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&#8217;s helpful if they are accurate.</simpara>
</section>
<section xml:id="_registering_a_secure_application">
<title>Registering a Secure Application</title>
<simpara>If your app wants to be contacted over HTTPS you can set two flags in
the <literal>EurekaInstanceConfig</literal>, <emphasis>viz</emphasis>
<literal>eureka.instance.[nonSecurePortEnabled,securePortEnabled]=[false,true]</literal>
respectively. This will make Eureka publish instance information
showing an explicit preference for secure communication. The Spring
Cloud <literal>DiscoveryClient</literal> will always return a URI starting with <literal>https</literal> for a
service configured this way, and the Eureka (native) instance
information will have a secure health check URL.</simpara>
<simpara>Because of the way
Eureka works internally, it will still publish a non-secure URL for
status and home page unless you also override those explicitly.
You can use placeholders to configure the eureka instance urls,
e.g.</simpara>
<formalpara>
<title>application.yml</title>
<para>
<screen>eureka:
instance:
statusPageUrl: https://${eureka.hostname}/info
healthCheckUrl: https://${eureka.hostname}/health
homePageUrl: https://${eureka.hostname}/</screen>
</para>
</formalpara>
<simpara>(Note that <literal>${eureka.hostname}</literal> is a native placeholder only available
in later versions of Eureka. You could achieve the same thing with
Spring placeholders as well, e.g. using <literal>${eureka.instance.hostName}</literal>.)</simpara>
<note>
<simpara>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).</simpara>
</note>
</section>
<section xml:id="_eureka_s_health_checks">
<title>Eureka&#8217;s Health Checks</title>
<simpara>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&#8217;t be sending
traffic to application in state other then 'UP'.</simpara>
<formalpara>
<title>application.yml</title>
<para>
<screen>eureka:
client:
healthcheck:
enabled: true</screen>
</para>
</formalpara>
<warning>
<simpara><literal>eureka.client.healthcheck.enabled=true</literal> should only be set in <literal>application.yml</literal>. Setting the value in <literal>bootstrap.yml</literal> will cause undesirable side effects like registering in eureka with an <literal>UNKNOWN</literal> status.</simpara>
</warning>
<simpara>If you require more control over the health checks, you may consider
implementing your own <literal>com.netflix.appinfo.HealthCheckHandler</literal>.</simpara>
</section>
<section xml:id="_eureka_metadata_for_instances_and_clients">
<title>Eureka Metadata for Instances and Clients</title>
<simpara>It&#8217;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 <literal>eureka.instance.metadataMap</literal>, 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.</simpara>
<section xml:id="_using_eureka_on_cloudfoundry">
<title>Using Eureka on Cloudfoundry</title>
<simpara>Cloudfoundry has a global router so that all instances of the same app have the same hostname (it&#8217;s the same in other PaaS solutions with a similar architecture). This isn&#8217;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 <literal>eureka.instance.instanceId</literal> is <literal>vcap.application.instance_id</literal>. For example:</simpara>
<formalpara>
<title>application.yml</title>
<para>
<screen>eureka:
instance:
hostname: ${vcap.application.uris[0]}
nonSecurePort: 80</screen>
</para>
</formalpara>
<simpara>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 (<link xl:href="https://run.pivotal.io">PWS</link>).</simpara>
</section>
<section xml:id="_using_eureka_on_aws">
<title>Using Eureka on AWS</title>
<simpara>If the application is planned to be deployed to an AWS cloud, then the Eureka instance will have to be configured to be AWS aware and this can be done by customizing the <link xl:href="http://github.com/spring-cloud/spring-cloud-netflix/tree/master/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaInstanceConfigBean.java">EurekaInstanceConfigBean</link> the following way:</simpara>
<programlisting language="java" linenumbering="unnumbered">@Bean
@Profile("!default")
public EurekaInstanceConfigBean eurekaInstanceConfig(InetUtils inetUtils) {
EurekaInstanceConfigBean b = new EurekaInstanceConfigBean(inetUtils);
AmazonInfo info = AmazonInfo.Builder.newBuilder().autoBuild("eureka");
b.setDataCenterInfo(info);
return b;
}</programlisting>
</section>
<section xml:id="_changing_the_eureka_instance_id">
<title>Changing the Eureka Instance ID</title>
<simpara>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: <literal>${spring.cloud.client.hostname}:${spring.application.name}:${spring.application.instance_id:${server.port}}}</literal>. For example <literal>myhost:myappname:8080</literal>.</simpara>
<simpara>Using Spring Cloud you can override this by providing a unique identifier in <literal>eureka.instance.instanceId</literal>. For example:</simpara>
<formalpara>
<title>application.yml</title>
<para>
<screen>eureka:
instance:
instanceId: ${spring.application.name}:${vcap.application.instance_id:${spring.application.instance_id:${random.value}}}</screen>
</para>
</formalpara>
<simpara>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 <literal>vcap.application.instance_id</literal> will be
populated automatically in a Spring Boot application, so the
random value will not be needed.</simpara>
</section>
</section>
<section xml:id="_using_the_eurekaclient">
<title>Using the EurekaClient</title>
<simpara>Once you have an app that is a discovery client you can use it to
discover service instances from the <link linkend="spring-cloud-eureka-server">Eureka Server</link>. One way to do that is to use the native
<literal>com.netflix.discovery.EurekaClient</literal> (as opposed to the Spring
Cloud <literal>DiscoveryClient</literal>), e.g.</simpara>
<screen>@Autowired
private EurekaClient discoveryClient;
public String serviceUrl() {
InstanceInfo instance = discoveryClient.getNextServerFromEureka("STORES", false);
return instance.getHomePageUrl();
}</screen>
<tip>
<simpara>Don&#8217;t use the <literal>EurekaClient</literal> in <literal>@PostConstruct</literal> method or in a
<literal>@Scheduled</literal> method (or anywhere where the <literal>ApplicationContext</literal> might
not be started yet). It is initialized in a <literal>SmartLifecycle</literal> (with
<literal>phase=0</literal>) so the earliest you can rely on it being available is in
another <literal>SmartLifecycle</literal> with higher phase.</simpara>
</tip>
<section xml:id="_eurekaclient_without_jersey">
<title>EurekaClient without Jersey</title>
<simpara>By default, EurekaClient uses Jersey for HTTP communication. If you wish
to avoid dependencies from Jersey, you can exclude it from your dependencies.
Spring Cloud will auto configure a transport client based on Spring
<literal>RestTemplate</literal>.</simpara>
<screen>&lt;dependency&gt;
&lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
&lt;artifactId&gt;spring-cloud-starter-netflix-eureka-client&lt;/artifactId&gt;
&lt;exclusions&gt;
&lt;exclusion&gt;
&lt;groupId&gt;com.sun.jersey&lt;/groupId&gt;
&lt;artifactId&gt;jersey-client&lt;/artifactId&gt;
&lt;/exclusion&gt;
&lt;exclusion&gt;
&lt;groupId&gt;com.sun.jersey&lt;/groupId&gt;
&lt;artifactId&gt;jersey-core&lt;/artifactId&gt;
&lt;/exclusion&gt;
&lt;exclusion&gt;
&lt;groupId&gt;com.sun.jersey.contribs&lt;/groupId&gt;
&lt;artifactId&gt;jersey-apache-client4&lt;/artifactId&gt;
&lt;/exclusion&gt;
&lt;/exclusions&gt;
&lt;/dependency&gt;</screen>
</section>
</section>
<section xml:id="_alternatives_to_the_native_netflix_eurekaclient">
<title>Alternatives to the native Netflix EurekaClient</title>
<simpara>You don&#8217;t have to use the raw Netflix <literal>EurekaClient</literal> and usually it
is more convenient to use it behind a wrapper of some sort. Spring
Cloud has support for <link linkend="spring-cloud-feign">Feign</link> (a REST client
builder) and also <link linkend="spring-cloud-ribbon">Spring <literal>RestTemplate</literal></link> 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 <literal>&lt;client&gt;.ribbon.listOfServers</literal> to a comma-separated
list of physical addresses (or hostnames), where <literal>&lt;client&gt;</literal> is the ID
of the client.</simpara>
<simpara>You can also use the <literal>org.springframework.cloud.client.discovery.DiscoveryClient</literal>
which provides a simple API for discovery clients that is not specific
to Netflix, e.g.</simpara>
<screen>@Autowired
private DiscoveryClient discoveryClient;
public String serviceUrl() {
List&lt;ServiceInstance&gt; list = discoveryClient.getInstances("STORES");
if (list != null &amp;&amp; list.size() &gt; 0 ) {
return list.get(0).getUri();
}
return null;
}</screen>
</section>
<section xml:id="_why_is_it_so_slow_to_register_a_service">
<title>Why is it so Slow to Register a Service?</title>
<simpara>Being an instance also involves a periodic heartbeat to the registry
(via the client&#8217;s <literal>serviceUrl</literal>) 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 heartbeats). You can change the period using
<literal>eureka.instance.leaseRenewalIntervalInSeconds</literal> and this will speed up
the process of getting clients connected to other services. In
production it&#8217;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.</simpara>
</section>
<section xml:id="_zones">
<title>Zones</title>
<simpara>If you have deployed Eureka clients to multiple zones than you may prefer that
those clients leverage services within the same zone before trying services
in another zone. To do this you need to configure your Eureka clients correctly.</simpara>
<simpara>First, you need to make sure you have Eureka servers deployed to each zone and that
they are peers of each other. See the section on <link linkend="spring-cloud-eureka-server-zones-and-regions">zones and regions</link>
for more information.</simpara>
<simpara>Next you need to tell Eureka which zone your service is in. You can do this using
the <literal>metadataMap</literal> property. For example if <literal>service 1</literal> is deployed to both <literal>zone 1</literal>
and <literal>zone 2</literal> you would need to set the following Eureka properties in <literal>service 1</literal></simpara>
<simpara><emphasis role="strong">Service 1 in Zone 1</emphasis></simpara>
<screen>eureka.instance.metadataMap.zone = zone1
eureka.client.preferSameZoneEureka = true</screen>
<simpara><emphasis role="strong">Service 1 in Zone 2</emphasis></simpara>
<screen>eureka.instance.metadataMap.zone = zone2
eureka.client.preferSameZoneEureka = true</screen>
</section>
</chapter>
<chapter xml:id="spring-cloud-eureka-server">
<title>Service Discovery: Eureka Server</title>
<section xml:id="netflix-eureka-server-starter">
<title>How to Include Eureka Server</title>
<simpara>To include Eureka Server in your project use the starter with group <literal>org.springframework.cloud</literal>
and artifact id <literal>spring-cloud-starter-netflix-eureka-server</literal>. See the <link xl:href="http://projects.spring.io/spring-cloud/">Spring Cloud Project page</link>
for details on setting up your build system with the current Spring Cloud Release Train.</simpara>
</section>
<section xml:id="spring-cloud-running-eureka-server">
<title>How to Run a Eureka Server</title>
<simpara>Example eureka server;</simpara>
<programlisting language="java" linenumbering="unnumbered">@SpringBootApplication
@EnableEurekaServer
public class Application {
public static void main(String[] args) {
new SpringApplicationBuilder(Application.class).web(true).run(args);
}
}</programlisting>
<simpara>The server has a home page with a UI, and HTTP API endpoints per the
normal Eureka functionality under <literal>/eureka/*</literal>.</simpara>
<simpara>Eureka background reading: see <link xl:href="https://github.com/cfregly/fluxcapacitor/wiki/NetflixOSS-FAQ#eureka-service-discovery-load-balancer">flux capacitor</link> and <link xl:href="https://groups.google.com/forum/?fromgroups#!topic/eureka_netflix/g3p2r7gHnN0">google group discussion</link>.</simpara>
<tip>
<simpara>Due to Gradle&#8217;s dependency resolution rules and the lack of a parent bom feature, simply depending on spring-cloud-starter-netflix-eureka-server can cause failures on application startup. To remedy this the Spring Boot Gradle plugin must be added and the Spring cloud starter parent bom must be imported like so:</simpara>
<formalpara>
<title>build.gradle</title>
<para>
<programlisting language="java" linenumbering="unnumbered">buildscript {
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:1.3.5.RELEASE")
}
}
apply plugin: "spring-boot"
dependencyManagement {
imports {
mavenBom "org.springframework.cloud:spring-cloud-dependencies:Brixton.RELEASE"
}
}</programlisting>
</para>
</formalpara>
</tip>
</section>
<section xml:id="spring-cloud-eureka-server-zones-and-regions">
<title>High Availability, Zones and Regions</title>
<simpara>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&#8217;t have to
go to the registry for every single request to a service).</simpara>
<simpara>By default every Eureka server is also a Eureka client and requires
(at least one) service URL to locate a peer. If you don&#8217;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.</simpara>
<simpara>See also <link linkend="spring-cloud-ribbon">below for details of Ribbon
support</link> on the client side for Zones and Regions.</simpara>
</section>
<section xml:id="_standalone_mode">
<title>Standalone Mode</title>
<simpara>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&#8217;t keep
trying and failing to reach its peers. Example:</simpara>
<formalpara>
<title>application.yml (Standalone Eureka Server)</title>
<para>
<screen>server:
port: 8761
eureka:
instance:
hostname: localhost
client:
registerWithEureka: false
fetchRegistry: false
serviceUrl:
defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/</screen>
</para>
</formalpara>
<simpara>Notice that the <literal>serviceUrl</literal> is pointing to the same host as the local
instance.</simpara>
</section>
<section xml:id="_peer_awareness">
<title>Peer Awareness</title>
<simpara>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 <literal>serviceUrl</literal> to a peer, e.g.</simpara>
<formalpara>
<title>application.yml (Two Peer Aware Eureka Servers)</title>
<para>
<screen>---
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/</screen>
</para>
</formalpara>
<simpara>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&#8217;s not much value in doing that in
production) by manipulating <literal>/etc/hosts</literal> to resolve the host names. In
fact, the <literal>eureka.instance.hostname</literal> is not needed if you are running
on a machine that knows its own hostname (it is looked up using
<literal>java.net.InetAddress</literal> by default).</simpara>
<simpara>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.</simpara>
</section>
<section xml:id="_prefer_ip_address">
<title>Prefer IP Address</title>
<simpara>In some cases, it is preferable for Eureka to advertise the IP Adresses
of services rather than the hostname. Set <literal>eureka.instance.preferIpAddress</literal>
to <literal>true</literal> and when the application registers with eureka, it will use its
IP Address rather than its hostname.</simpara>
<tip>
<simpara>If hostname can&#8217;t be determined by Java, then IP address is sent to Eureka.
Only explict way of setting hostname is by using <literal>eureka.instance.hostname</literal>.
You can set your hostname at the run time using environment variable, for
example <literal>eureka.instance.hostname=${HOST_NAME}</literal>.</simpara>
</tip>
</section>
</chapter>
<chapter xml:id="_circuit_breaker_hystrix_clients">
<title>Circuit Breaker: Hystrix Clients</title>
<simpara>Netflix has created a library called <link xl:href="https://github.com/Netflix/Hystrix">Hystrix</link> that implements the <link xl:href="http://martinfowler.com/bliki/CircuitBreaker.html">circuit breaker pattern</link>. In a microservice architecture it is common to have multiple layers of service calls.</simpara>
<figure>
<title>Microservice Graph</title>
<mediaobject>
<imageobject>
<imagedata fileref="images/HystrixGraph.png"/>
</imageobject>
<textobject><phrase>HystrixGraph</phrase></textobject>
</mediaobject>
</figure>
<simpara>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 is greater than <literal>circuitBreaker.requestVolumeThreshold</literal> (default: 20 requests) and failue percentage is greater than <literal>circuitBreaker.errorThresholdPercentage</literal> (default: &gt;50%) in a rolling window defined by <literal>metrics.rollingStats.timeInMilliseconds</literal> (default: 10 seconds), 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.</simpara>
<figure>
<title>Hystrix fallback prevents cascading failures</title>
<mediaobject>
<imageobject>
<imagedata fileref="images/HystrixFallback.png"/>
</imageobject>
<textobject><phrase>HystrixFallback</phrase></textobject>
</mediaobject>
</figure>
<simpara>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.</simpara>
<section xml:id="netflix-hystrix-starter">
<title>How to Include Hystrix</title>
<simpara>To include Hystrix in your project use the starter with group <literal>org.springframework.cloud</literal>
and artifact id <literal>spring-cloud-starter-netflix-hystrix</literal>. See the <link xl:href="http://projects.spring.io/spring-cloud/">Spring Cloud Project page</link>
for details on setting up your build system with the current Spring Cloud Release Train.</simpara>
<simpara>Example boot app:</simpara>
<screen>@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&lt;String, Object&gt; parameters) {
//do stuff that might fail
}
public Object defaultStores(Map&lt;String, Object&gt; parameters) {
return /* something useful */;
}
}</screen>
<simpara>The <literal>@HystrixCommand</literal> is provided by a Netflix contrib library called
<link xl:href="https://github.com/Netflix/Hystrix/tree/master/hystrix-contrib/hystrix-javanica">"javanica"</link>.
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.</simpara>
<simpara>To configure the <literal>@HystrixCommand</literal> you can use the <literal>commandProperties</literal>
attribute with a list of <literal>@HystrixProperty</literal> annotations. See
<link xl:href="https://github.com/Netflix/Hystrix/tree/master/hystrix-contrib/hystrix-javanica#configuration">here</link>
for more details. See the <link xl:href="https://github.com/Netflix/Hystrix/wiki/Configuration">Hystrix wiki</link>
for details on the properties available.</simpara>
</section>
<section xml:id="_propagating_the_security_context_or_using_spring_scopes">
<title>Propagating the Security Context or using Spring Scopes</title>
<simpara>If you want some thread local context to propagate into a <literal>@HystrixCommand</literal> 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:</simpara>
<programlisting language="java" linenumbering="unnumbered">@HystrixCommand(fallbackMethod = "stubMyService",
commandProperties = {
@HystrixProperty(name="execution.isolation.strategy", value="SEMAPHORE")
}
)
...</programlisting>
<simpara>The same thing applies if you are using <literal>@SessionScope</literal> or <literal>@RequestScope</literal>. You will know when you need to do this because of a runtime exception that says it can&#8217;t find the scoped context.</simpara>
<simpara>You also have the option to set the <literal>hystrix.shareSecurityContext</literal> property to <literal>true</literal>. Doing so will auto configure an Hystrix concurrency strategy plugin hook who will transfer the <literal>SecurityContext</literal> from your main thread to the one used by the Hystrix command. Hystrix does not allow multiple hystrix concurrency strategy to be registered so an extension mechanism is available by declaring your own <literal>HystrixConcurrencyStrategy</literal> as a Spring bean. Spring Cloud will lookup for your implementation within the Spring context and wrap it inside its own plugin.</simpara>
</section>
<section xml:id="_health_indicator">
<title>Health Indicator</title>
<simpara>The state of the connected circuit breakers are also exposed in the
<literal>/health</literal> endpoint of the calling application.</simpara>
<programlisting language="json" linenumbering="unnumbered">{
"hystrix": {
"openCircuitBreakers": [
"StoreIntegration::getStoresByLocationLink"
],
"status": "CIRCUIT_OPEN"
},
"status": "UP"
}</programlisting>
</section>
<section xml:id="_hystrix_metrics_stream">
<title>Hystrix Metrics Stream</title>
<simpara>To enable the Hystrix metrics stream include a dependency on <literal>spring-boot-starter-actuator</literal>. This will expose the <literal>/hystrix.stream</literal> as a management endpoint.</simpara>
<programlisting language="xml" linenumbering="unnumbered"> &lt;dependency&gt;
&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
&lt;artifactId&gt;spring-boot-starter-actuator&lt;/artifactId&gt;
&lt;/dependency&gt;</programlisting>
</section>
</chapter>
<chapter xml:id="_circuit_breaker_hystrix_dashboard">
<title>Circuit Breaker: Hystrix Dashboard</title>
<simpara>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.</simpara>
<figure>
<title>Hystrix Dashboard</title>
<mediaobject>
<imageobject>
<imagedata fileref="images/Hystrix.png"/>
</imageobject>
<textobject><phrase>Hystrix</phrase></textobject>
</mediaobject>
</figure>
</chapter>
<chapter xml:id="_hystrix_timeouts_and_ribbon_clients">
<title>Hystrix Timeouts And Ribbon Clients</title>
<simpara>When using Hystrix commands that wrap Ribbon clients you want to make sure your Hystrix timeout
is configured to be longer than the configured Ribbon timeout, including any potential
retries that might be made. For example, if your Ribbon connection timeout is one second and
the Ribbon client might retry the request three times, than your Hystrix timeout should
be slightly more than three seconds.</simpara>
<section xml:id="netflix-hystrix-dashboard-starter">
<title>How to Include Hystrix Dashboard</title>
<simpara>To include the Hystrix Dashboard in your project use the starter with group <literal>org.springframework.cloud</literal>
and artifact id <literal>spring-cloud-starter-hystrix-netflix-dashboard</literal>. See the <link xl:href="http://projects.spring.io/spring-cloud/">Spring Cloud Project page</link>
for details on setting up your build system with the current Spring Cloud Release Train.</simpara>
<simpara>To run the Hystrix Dashboard annotate your Spring Boot main class with <literal>@EnableHystrixDashboard</literal>. You then visit <literal>/hystrix</literal> and point the dashboard to an individual instances <literal>/hystrix.stream</literal> endpoint in a Hystrix client application.</simpara>
<note>
<simpara>When connecting to a <literal>/hystrix.stream</literal> endpoint which uses HTTPS the certificate used by the server
must be trusted by the JVM. If the certificate is not trusted you must import the certificate into the JVM
in order for the Hystrix Dashboard to make a successful connection to the stream endpoint.</simpara>
</note>
</section>
<section xml:id="_turbine">
<title>Turbine</title>
<simpara>Looking at an individual instances Hystrix data is not very useful in terms of the overall health of the system. <link xl:href="https://github.com/Netflix/Turbine">Turbine</link> is an application that aggregates all of the relevant <literal>/hystrix.stream</literal> endpoints into a combined <literal>/turbine.stream</literal> for use in the Hystrix Dashboard. Individual instances are located via Eureka. Running Turbine is as simple as annotating your main class with the <literal>@EnableTurbine</literal> annotation (e.g. using spring-cloud-starter-netflix-turbine to set up the classpath). All of the documented configuration properties from <link xl:href="https://github.com/Netflix/Turbine/wiki/Configuration-(1.x)">the Turbine 1 wiki</link> apply. The only difference is that the <literal>turbine.instanceUrlSuffix</literal> does not need the port prepended as this is handled automatically unless <literal>turbine.instanceInsertPort=false</literal>.</simpara>
<note>
<simpara>By default, Turbine looks for the <literal>/hystrix.stream</literal> endpoint on a registered instance by looking up its <literal>hostName</literal> and <literal>port</literal> entries in Eureka, then appending <literal>/hystrix.stream</literal> to it.
If the instance&#8217;s metadata contains <literal>management.port</literal>, it will be used instead of the <literal>port</literal> value for the <literal>/hystrix.stream</literal> endpoint.
By default, metadata entry <literal>management.port</literal> is equal to the <literal>management.port</literal> configuration property, it can be overridden though with following configuration:</simpara>
</note>
<screen>eureka:
instance:
metadata-map:
management.port: ${management.port:8081}</screen>
<simpara>The configuration key <literal>turbine.appConfig</literal> 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: <literal><link xl:href="http://my.turbine.sever:8080/turbine.stream?cluster=CLUSTERNAME">http://my.turbine.sever:8080/turbine.stream?cluster=CLUSTERNAME</link></literal> (the cluster parameter can be omitted if the name is "default"). The <literal>cluster</literal> parameter must match an entry in <literal>turbine.aggregator.clusterConfig</literal>. Values returned from eureka are uppercase, thus we expect this example to work if there is an app registered with Eureka called "customers":</simpara>
<screen>turbine:
aggregator:
clusterConfig: CUSTOMERS
appConfig: customers</screen>
<simpara>If you need to customize which cluster names should be used by Turbine (you don&#8217;t want to store cluster names in
<literal>turbine.aggregator.clusterConfig</literal> configuration) provide a bean of type <literal>TurbineClustersProvider</literal>.</simpara>
<simpara>The <literal>clusterName</literal> can be customized by a SPEL expression in <literal>turbine.clusterNameExpression</literal> with root an instance of <literal>InstanceInfo</literal>. The default value is <literal>appName</literal>, which means that the Eureka serviceId ends up as the cluster key (i.e. the <literal>InstanceInfo</literal> for customers has an <literal>appName</literal> of "CUSTOMERS"). A different example would be <literal>turbine.clusterNameExpression=aSGName</literal>, which would get the cluster name from the AWS ASG name. Another example:</simpara>
<screen>turbine:
aggregator:
clusterConfig: SYSTEM,USER
appConfig: customers,stores,ui,admin
clusterNameExpression: metadata['cluster']</screen>
<simpara>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".</simpara>
<simpara>To use the "default" cluster for all apps you need a string literal expression (with single quotes, and escaped with double quotes if it is in YAML as well):</simpara>
<screen>turbine:
appConfig: customers,stores
clusterNameExpression: "'default'"</screen>
<simpara>Spring Cloud provides a <literal>spring-cloud-starter-netflix-turbine</literal> that has all the dependencies you need to get a Turbine server running. Just create a Spring Boot application and annotate it with <literal>@EnableTurbine</literal>.</simpara>
<note>
<simpara>by default Spring Cloud allows Turbine to use the host and port to allow multiple processes per host, per cluster. If you want the native Netflix behaviour built into Turbine that does <emphasis>not</emphasis> allow multiple processes per host, per cluster (the key to the instance id is the hostname), then set the property <literal>turbine.combineHostPort=false</literal>.</simpara>
</note>
</section>
<section xml:id="_turbine_stream">
<title>Turbine Stream</title>
<simpara>In some environments (e.g. in a PaaS setting), the classic Turbine model of pulling metrics from all the distributed Hystrix commands doesn&#8217;t work. In that case you might want to have your Hystrix commands push metrics to Turbine, and Spring Cloud enables that with messaging. All you need to do on the client is add a dependency to <literal>spring-cloud-netflix-hystrix-stream</literal> and the <literal>spring-cloud-starter-stream-*</literal> of your choice (see Spring Cloud Stream documentation for details on the brokers, and how to configure the client credentials, but it should work out of the box for a local broker).</simpara>
<simpara>On the server side Just create a Spring Boot application and annotate it with <literal>@EnableTurbineStream</literal> 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 <literal>server.port</literal> or <literal>turbine.stream.port</literal>. If you have <literal>spring-boot-starter-web</literal> and <literal>spring-boot-starter-actuator</literal> on the classpath as well, then you can open up the Actuator endpoints on a separate port (with Tomcat by default) by providing a <literal>management.port</literal> which is different.</simpara>
<simpara>You can then point the Hystrix Dashboard to the Turbine Stream Server instead of individual Hystrix streams. If Turbine Stream is running on port 8989 on myhost, then put <literal><link xl:href="http://myhost:8989">http://myhost:8989</link></literal> 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.</simpara>
<simpara>Spring Cloud provides a <literal>spring-cloud-starter-netflix-turbine-stream</literal> that has all the dependencies you need to get a Turbine Stream server running - just add the Stream binder of your choice, e.g. <literal>spring-cloud-starter-stream-rabbit</literal>. You need Java 8 to run the app because it is Netty-based.</simpara>
</section>
</chapter>
<chapter xml:id="spring-cloud-ribbon">
<title>Client Side Load Balancer: Ribbon</title>
<simpara>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 <literal>@FeignClient</literal> then this section also applies.</simpara>
<simpara>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 <literal>@FeignClient</literal>
annotation). Spring Cloud creates a new ensemble as an
<literal>ApplicationContext</literal> on demand for each named client using
<literal>RibbonClientConfiguration</literal>. This contains (amongst other things) an
<literal>ILoadBalancer</literal>, a <literal>RestClient</literal>, and a <literal>ServerListFilter</literal>.</simpara>
<section xml:id="netflix-ribbon-starter">
<title>How to Include Ribbon</title>
<simpara>To include Ribbon in your project use the starter with group <literal>org.springframework.cloud</literal>
and artifact id <literal>spring-cloud-starter-netflix-ribbon</literal>. See the <link xl:href="http://projects.spring.io/spring-cloud/">Spring Cloud Project page</link>
for details on setting up your build system with the current Spring Cloud Release Train.</simpara>
</section>
<section xml:id="_customizing_the_ribbon_client">
<title>Customizing the Ribbon Client</title>
<simpara>You can configure some bits of a Ribbon client using external
properties in <literal>&lt;client&gt;.ribbon.*</literal>, 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 <link xl:href="https://github.com/Netflix/ribbon/blob/master/ribbon-core/src/main/java/com/netflix/client/config/CommonClientConfigKey.java"><literal>CommonClientConfigKey</literal></link> (part of
ribbon-core).</simpara>
<simpara>Spring Cloud also lets you take full control of the client by
declaring additional configuration (on top of the
<literal>RibbonClientConfiguration</literal>) using <literal>@RibbonClient</literal>. Example:</simpara>
<programlisting language="java" linenumbering="unnumbered">@Configuration
@RibbonClient(name = "foo", configuration = FooConfiguration.class)
public class TestConfiguration {
}</programlisting>
<simpara>In this case the client is composed from the components already in
<literal>RibbonClientConfiguration</literal> together with any in <literal>FooConfiguration</literal>
(where the latter generally will override the former).</simpara>
<warning>
<simpara>The <literal>FooConfiguration</literal> has to be <literal>@Configuration</literal> but take
care that it is not in a <literal>@ComponentScan</literal> for the main application
context, otherwise it will be shared by all the <literal>@RibbonClients</literal>. If
you use <literal>@ComponentScan</literal> (or <literal>@SpringBootApplication</literal>) 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 <literal>@ComponentScan</literal>).</simpara>
</warning>
<simpara>Spring Cloud Netflix provides the following beans by default for ribbon
(<literal>BeanType</literal> beanName: <literal>ClassName</literal>):</simpara>
<itemizedlist>
<listitem>
<simpara><literal>IClientConfig</literal> ribbonClientConfig: <literal>DefaultClientConfigImpl</literal></simpara>
</listitem>
<listitem>
<simpara><literal>IRule</literal> ribbonRule: <literal>ZoneAvoidanceRule</literal></simpara>
</listitem>
<listitem>
<simpara><literal>IPing</literal> ribbonPing: <literal>DummyPing</literal></simpara>
</listitem>
<listitem>
<simpara><literal>ServerList&lt;Server&gt;</literal> ribbonServerList: <literal>ConfigurationBasedServerList</literal></simpara>
</listitem>
<listitem>
<simpara><literal>ServerListFilter&lt;Server&gt;</literal> ribbonServerListFilter: <literal>ZonePreferenceServerListFilter</literal></simpara>
</listitem>
<listitem>
<simpara><literal>ILoadBalancer</literal> ribbonLoadBalancer: <literal>ZoneAwareLoadBalancer</literal></simpara>
</listitem>
<listitem>
<simpara><literal>ServerListUpdater</literal> ribbonServerListUpdater: <literal>PollingServerListUpdater</literal></simpara>
</listitem>
</itemizedlist>
<simpara>Creating a bean of one of those type and placing it in a <literal>@RibbonClient</literal>
configuration (such as <literal>FooConfiguration</literal> above) allows you to override each
one of the beans described. Example:</simpara>
<programlisting language="java" linenumbering="unnumbered">@Configuration
protected static class FooConfiguration {
@Bean
public ZonePreferenceServerListFilter serverListFilter() {
ZonePreferenceServerListFilter filter = new ZonePreferenceServerListFilter();
filter.setZone("myTestZone");
return filter;
}
@Bean
public IPing ribbonPing() {
return new PingUrl();
}
}</programlisting>
<simpara>This replaces the <literal>NoOpPing</literal> with <literal>PingUrl</literal> and provides a custom <literal>serverListFilter</literal></simpara>
</section>
<section xml:id="_customizing_default_for_all_ribbon_clients">
<title>Customizing default for all Ribbon Clients</title>
<simpara>A default configuration can be provided for all Ribbon Clients using the <literal>@RibbonClients</literal> annotation and registering a default configuration as shown in the following example:</simpara>
<programlisting language="java" linenumbering="unnumbered">@RibbonClients(defaultConfiguration = DefaultRibbonConfig.class)
public class RibbonClientDefaultConfigurationTestsConfig {
public static class BazServiceList extends ConfigurationBasedServerList {
public BazServiceList(IClientConfig config) {
super.initWithNiwsConfig(config);
}
}
}
@Configuration
class DefaultRibbonConfig {
@Bean
public IRule ribbonRule() {
return new BestAvailableRule();
}
@Bean
public IPing ribbonPing() {
return new PingUrl();
}
@Bean
public ServerList&lt;Server&gt; ribbonServerList(IClientConfig config) {
return new RibbonClientDefaultConfigurationTestsConfig.BazServiceList(config);
}
@Bean
public ServerListSubsetFilter serverListFilter() {
ServerListSubsetFilter filter = new ServerListSubsetFilter();
return filter;
}
}</programlisting>
</section>
<section xml:id="_customizing_the_ribbon_client_using_properties">
<title>Customizing the Ribbon Client using properties</title>
<simpara>Starting with version 1.2.0, Spring Cloud Netflix now supports customizing Ribbon clients using properties to be compatible with the <link xl:href="https://github.com/Netflix/ribbon/wiki/Working-with-load-balancers#components-of-load-balancer">Ribbon documentation</link>.</simpara>
<simpara>This allows you to change behavior at start up time in different environments.</simpara>
<simpara>The supported properties are listed below and should be prefixed by <literal>&lt;clientName&gt;.ribbon.</literal>:</simpara>
<itemizedlist>
<listitem>
<simpara><literal>NFLoadBalancerClassName</literal>: should implement <literal>ILoadBalancer</literal></simpara>
</listitem>
<listitem>
<simpara><literal>NFLoadBalancerRuleClassName</literal>: should implement <literal>IRule</literal></simpara>
</listitem>
<listitem>
<simpara><literal>NFLoadBalancerPingClassName</literal>: should implement <literal>IPing</literal></simpara>
</listitem>
<listitem>
<simpara><literal>NIWSServerListClassName</literal>: should implement <literal>ServerList</literal></simpara>
</listitem>
<listitem>
<simpara><literal>NIWSServerListFilterClassName</literal> should implement <literal>ServerListFilter</literal></simpara>
</listitem>
</itemizedlist>
<note>
<simpara>Classes defined in these properties have precedence over beans defined using <literal>@RibbonClient(configuration=MyRibbonConfig.class)</literal> and the defaults provided by Spring Cloud Netflix.</simpara>
</note>
<simpara>To set the <literal>IRule</literal> for a service name <literal>users</literal> you could set the following:</simpara>
<formalpara>
<title>application.yml</title>
<para>
<screen>users:
ribbon:
NIWSServerListClassName: com.netflix.loadbalancer.ConfigurationBasedServerList
NFLoadBalancerRuleClassName: com.netflix.loadbalancer.WeightedResponseTimeRule</screen>
</para>
</formalpara>
<simpara>See the <link xl:href="https://github.com/Netflix/ribbon/wiki/Working-with-load-balancers">Ribbon documentation</link> for implementations provided by Ribbon.</simpara>
</section>
<section xml:id="_using_ribbon_with_eureka">
<title>Using Ribbon with Eureka</title>
<simpara>When Eureka is used in conjunction with Ribbon (i.e., both are on the classpath) the <literal>ribbonServerList</literal>
is overridden with an extension of <literal>DiscoveryEnabledNIWSServerList</literal>
which populates the list of servers from Eureka. It also replaces the
<literal>IPing</literal> interface with <literal>NIWSDiscoveryPing</literal> which delegates to Eureka
to determine if a server is up. The <literal>ServerList</literal> that is installed by
default is a <literal>DomainExtractingServerList</literal> 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 remote clients set
<literal>eureka.instance.metadataMap.zone</literal>), and if that is missing it can use
the domain name from the server hostname as a proxy for zone (if the
flag <literal>approximateZoneFromHostname</literal> is set). Once the zone information
is available it can be used in a <literal>ServerListFilter</literal>. By default it
will be used to locate a server in the same zone as the client because
the default is a <literal>ZonePreferenceServerListFilter</literal>. The zone of the
client is determined the same way as the remote instances by default,
i.e. via <literal>eureka.instance.metadataMap.zone</literal>.</simpara>
<note>
<simpara>The orthodox "archaius" way to set the client zone is via a
configuration property called "@zone", and Spring Cloud will use that
in preference to all other settings if it is available (note that the
key will have to be quoted in YAML configuration).</simpara>
</note>
<note>
<simpara>If there is no other source of zone data then a guess is made
based on the client configuration (as opposed to the instance
configuration). We take <literal>eureka.client.availabilityZones</literal>, which is a
map from region name to a list of zones, and pull out the first zone
for the instance&#8217;s own region (i.e. the <literal>eureka.client.region</literal>, which
defaults to "us-east-1" for comatibility with native Netflix).</simpara>
</note>
</section>
<section xml:id="spring-cloud-ribbon-without-eureka">
<title>Example: How to Use Ribbon Without Eureka</title>
<simpara>Eureka is a convenient way to abstract the discovery of remote servers
so you don&#8217;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 <literal>@RibbonClient</literal> 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</simpara>
<formalpara>
<title>application.yml</title>
<para>
<screen>stores:
ribbon:
listOfServers: example.com,google.com</screen>
</para>
</formalpara>
</section>
<section xml:id="_example_disable_eureka_use_in_ribbon">
<title>Example: Disable Eureka use in Ribbon</title>
<simpara>Setting the property <literal>ribbon.eureka.enabled = false</literal> will explicitly
disable the use of Eureka in Ribbon.</simpara>
<formalpara>
<title>application.yml</title>
<para>
<screen>ribbon:
eureka:
enabled: false</screen>
</para>
</formalpara>
</section>
<section xml:id="_using_the_ribbon_api_directly">
<title>Using the Ribbon API Directly</title>
<simpara>You can also use the <literal>LoadBalancerClient</literal> directly. Example:</simpara>
<programlisting language="java" linenumbering="unnumbered">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
}
}</programlisting>
</section>
<section xml:id="ribbon-child-context-eager-load">
<title>Caching of Ribbon Configuration</title>
<simpara>Each Ribbon named client has a corresponding child Application Context that Spring Cloud maintains, this application context is lazily loaded up on the first request to the named client.
This lazy loading behavior can be changed to instead eagerly load up these child Application contexts at startup by specifying the names of the Ribbon clients.</simpara>
<formalpara>
<title>application.yml</title>
<para>
<screen>ribbon:
eager-load:
enabled: true
clients: client1, client2, client3</screen>
</para>
</formalpara>
</section>
<section xml:id="how-to-configure-hystrix-thread-pools">
<title>How to Configure Hystrix thread pools</title>
<simpara>If you change <literal>zuul.ribbonIsolationStrategy</literal> to THREAD, the thread isolation strategy for Hystrix will be used for all routes. In this case, the HystrixThreadPoolKey is set to "RibbonCommand" as default. It means that HystrixCommands for all routes will be executed in the same Hystrix thread pool. This behavior can be changed using the following configuration and it will result in HystrixCommands being executed in the Hystrix thread pool for each route.</simpara>
<formalpara>
<title>application.yml</title>
<para>
<screen>zuul:
threadPool:
useSeparateThreadPools: true</screen>
</para>
</formalpara>
<simpara>The default HystrixThreadPoolKey in this case is same with service ID for each route. To add a prefix to HystrixThreadPoolKey, set <literal>zuul.threadPool.threadPoolKeyPrefix</literal> to a value that you want to add. For example:</simpara>
<formalpara>
<title>application.yml</title>
<para>
<screen>zuul:
threadPool:
useSeparateThreadPools: true
threadPoolKeyPrefix: zuulgw</screen>
</para>
</formalpara>
</section>
<section xml:id="how-to-provdie-a-key-to-ribbon">
<title>How to Provide a Key to Ribbon&#8217;s <literal>IRule</literal></title>
<simpara>If you need to provide your own <literal>IRule</literal> implementation to handle a special routing requirement like a canary test,
you probably want to pass some information to the <literal>choose</literal> method of <literal>IRule</literal>.</simpara>
<formalpara>
<title>com.netflix.loadbalancer.IRule.java</title>
<para>
<screen>public interface IRule{
public Server choose(Object key);
:</screen>
</para>
</formalpara>
<simpara>You can provide some information that will be used to choose a target server by your <literal>IRule</literal> implementation like
the following:</simpara>
<screen>RequestContext.getCurrentContext()
.set(FilterConstants.LOAD_BALANCER_KEY, "canary-test");</screen>
<simpara>If you put any object into the <literal>RequestContext</literal> with a key <literal>FilterConstants.LOAD_BALANCER_KEY</literal>, it will
be passed to the <literal>choose</literal> method of <literal>IRule</literal> implementation. Above code must be executed before <literal>RibbonRoutingFilter</literal>
is executed and Zuul&#8217;s pre filter is the best place to do that. You can easily access HTTP headers and query parameters
via <literal>RequestContext</literal> in pre filter, so it can be used to determine <literal>LOAD_BALANCER_KEY</literal> that will be passed to Ribbon.
If you don&#8217;t put any value with <literal>LOAD_BALANCER_KEY</literal> in <literal>RequestContext</literal>, null will be passed as a parameter of <literal>choose</literal>
method.</simpara>
</section>
</chapter>
<chapter xml:id="spring-cloud-feign">
<title>Declarative REST Client: Feign</title>
<simpara><link xl:href="https://github.com/Netflix/feign">Feign</link> 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 <literal>HttpMessageConverters</literal> used by default in Spring Web. Spring Cloud integrates Ribbon and Eureka to provide a load balanced http client when using Feign.</simpara>
<section xml:id="netflix-feign-starter">
<title>How to Include Feign</title>
<simpara>To include Feign in your project use the starter with group <literal>org.springframework.cloud</literal>
and artifact id <literal>spring-cloud-starter-openfeign</literal>. See the <link xl:href="http://projects.spring.io/spring-cloud/">Spring Cloud Project page</link>
for details on setting up your build system with the current Spring Cloud Release Train.</simpara>
<simpara>Example spring boot app</simpara>
<programlisting language="java" linenumbering="unnumbered">@SpringBootApplication
@EnableFeignClients
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}</programlisting>
<formalpara>
<title>StoreClient.java</title>
<para>
<programlisting language="java" linenumbering="unnumbered">@FeignClient("stores")
public interface StoreClient {
@RequestMapping(method = RequestMethod.GET, value = "/stores")
List&lt;Store&gt; getStores();
@RequestMapping(method = RequestMethod.POST, value = "/stores/{storeId}", consumes = "application/json")
Store update(@PathVariable("storeId") Long storeId, Store store);
}</programlisting>
</para>
</formalpara>
<simpara>In the <literal>@FeignClient</literal> annotation the String value ("stores" above) is
an arbitrary client name, which is used to create a Ribbon load
balancer (see <link linkend="spring-cloud-ribbon">below for details of Ribbon
support</link>). You can also specify a URL using the <literal>url</literal> attribute
(absolute value or just a hostname). The name of the bean in the
application context is the fully qualified name of the interface.
To specify your own alias value you can use the <literal>qualifier</literal> value
of the <literal>@FeignClient</literal> annotation.</simpara>
<simpara>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&#8217;t want to use Eureka, you can simply configure a list of servers
in your external configuration (see
<link linkend="spring-cloud-ribbon-without-eureka">above for example</link>).</simpara>
</section>
<section xml:id="spring-cloud-feign-overriding-defaults">
<title>Overriding Feign Defaults</title>
<simpara>A central concept in Spring Cloud&#8217;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 <literal>@FeignClient</literal> annotation. Spring Cloud creates a new ensemble as an
<literal>ApplicationContext</literal> on demand for each named client using <literal>FeignClientsConfiguration</literal>. This contains (amongst other things) an <literal>feign.Decoder</literal>, a <literal>feign.Encoder</literal>, and a <literal>feign.Contract</literal>.</simpara>
<simpara>Spring Cloud lets you take full control of the feign client by declaring additional configuration (on top of the <literal>FeignClientsConfiguration</literal>) using <literal>@FeignClient</literal>. Example:</simpara>
<programlisting language="java" linenumbering="unnumbered">@FeignClient(name = "stores", configuration = FooConfiguration.class)
public interface StoreClient {
//..
}</programlisting>
<simpara>In this case the client is composed from the components already in <literal>FeignClientsConfiguration</literal> together with any in <literal>FooConfiguration</literal> (where the latter will override the former).</simpara>
<note>
<simpara><literal>FooConfiguration</literal> does not need to be annotated with <literal>@Configuration</literal>. However, if it is, then take care to exclude it from any <literal>@ComponentScan</literal> that would otherwise include this configuration as it will become the default source for <literal>feign.Decoder</literal>, <literal>feign.Encoder</literal>, <literal>feign.Contract</literal>, etc., when specified. This can be avoided by putting it in a separate, non-overlapping package from any <literal>@ComponentScan</literal> or <literal>@SpringBootApplication</literal>, or it can be explicitly excluded in <literal>@ComponentScan</literal>.</simpara>
</note>
<note>
<simpara>The <literal>serviceId</literal> attribute is now deprecated in favor of the <literal>name</literal> attribute.</simpara>
</note>
<warning>
<simpara>Previously, using the <literal>url</literal> attribute, did not require the <literal>name</literal> attribute. Using <literal>name</literal> is now required.</simpara>
</warning>
<simpara>Placeholders are supported in the <literal>name</literal> and <literal>url</literal> attributes.</simpara>
<programlisting language="java" linenumbering="unnumbered">@FeignClient(name = "${feign.name}", url = "${feign.url}")
public interface StoreClient {
//..
}</programlisting>
<simpara>Spring Cloud Netflix provides the following beans by default for feign (<literal>BeanType</literal> beanName: <literal>ClassName</literal>):</simpara>
<itemizedlist>
<listitem>
<simpara><literal>Decoder</literal> feignDecoder: <literal>ResponseEntityDecoder</literal> (which wraps a <literal>SpringDecoder</literal>)</simpara>
</listitem>
<listitem>
<simpara><literal>Encoder</literal> feignEncoder: <literal>SpringEncoder</literal></simpara>
</listitem>
<listitem>
<simpara><literal>Logger</literal> feignLogger: <literal>Slf4jLogger</literal></simpara>
</listitem>
<listitem>
<simpara><literal>Contract</literal> feignContract: <literal>SpringMvcContract</literal></simpara>
</listitem>
<listitem>
<simpara><literal>Feign.Builder</literal> feignBuilder: <literal>HystrixFeign.Builder</literal></simpara>
</listitem>
<listitem>
<simpara><literal>Client</literal> feignClient: if Ribbon is enabled it is a <literal>LoadBalancerFeignClient</literal>, otherwise the default feign client is used.</simpara>
</listitem>
</itemizedlist>
<simpara>The OkHttpClient and ApacheHttpClient feign clients can be used by setting <literal>feign.okhttp.enabled</literal> or <literal>feign.httpclient.enabled</literal> to <literal>true</literal>, respectively, and having them on the classpath.
You can customize the HTTP client used by providing a bean of either <literal>ClosableHttpClient</literal> when using Apache or <literal>OkHttpClient</literal> whe using OK HTTP.</simpara>
<simpara>Spring Cloud Netflix <emphasis>does not</emphasis> 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:</simpara>
<itemizedlist>
<listitem>
<simpara><literal>Logger.Level</literal></simpara>
</listitem>
<listitem>
<simpara><literal>Retryer</literal></simpara>
</listitem>
<listitem>
<simpara><literal>ErrorDecoder</literal></simpara>
</listitem>
<listitem>
<simpara><literal>Request.Options</literal></simpara>
</listitem>
<listitem>
<simpara><literal>Collection&lt;RequestInterceptor&gt;</literal></simpara>
</listitem>
<listitem>
<simpara><literal>SetterFactory</literal></simpara>
</listitem>
</itemizedlist>
<simpara>Creating a bean of one of those type and placing it in a <literal>@FeignClient</literal> configuration (such as <literal>FooConfiguration</literal> above) allows you to override each one of the beans described. Example:</simpara>
<programlisting language="java" linenumbering="unnumbered">@Configuration
public class FooConfiguration {
@Bean
public Contract feignContract() {
return new feign.Contract.Default();
}
@Bean
public BasicAuthRequestInterceptor basicAuthRequestInterceptor() {
return new BasicAuthRequestInterceptor("user", "password");
}
}</programlisting>
<simpara>This replaces the <literal>SpringMvcContract</literal> with <literal>feign.Contract.Default</literal> and adds a <literal>RequestInterceptor</literal> to the collection of <literal>RequestInterceptor</literal>.</simpara>
<simpara><literal>@FeignClient</literal> also can be configured using configuration properties.</simpara>
<simpara>application.yml</simpara>
<programlisting language="yaml" linenumbering="unnumbered">feign:
client:
config:
feignName:
connectTimeout: 5000
readTimeout: 5000
loggerLevel: full
errorDecoder: com.example.SimpleErrorDecoder
retryer: com.example.SimpleRetryer
requestInterceptors:
- com.example.FooRequestInterceptor
- com.example.BarRequestInterceptor
decode404: false</programlisting>
<simpara>Default configurations can be specified in the <literal>@EnableFeignClients</literal> attribute <literal>defaultConfiguration</literal> in a similar manner as described above. The difference is that this configuration will apply to <emphasis>all</emphasis> feign clients.</simpara>
<simpara>If you prefer using configuration properties to configured all <literal>@FeignClient</literal>, you can create configuration properties with <literal>default</literal> feign name.</simpara>
<simpara>application.yml</simpara>
<programlisting language="yaml" linenumbering="unnumbered">feign:
client:
config:
default:
connectTimeout: 5000
readTimeout: 5000
loggerLevel: basic</programlisting>
<simpara>If we create both <literal>@Configuration</literal> bean and configuration properties, configuration properties will win.
It will override <literal>@Configuration</literal> values. But if you want to change the priority to <literal>@Configuration</literal>,
you can change <literal>feign.client.default-to-properties</literal> to <literal>false</literal>.</simpara>
<note>
<simpara>If you need to use <literal>ThreadLocal</literal> bound variables in your <literal>RequestInterceptor`s you will need to either set the
thread isolation strategy for Hystrix to `SEMAPHORE</literal> or disable Hystrix in Feign.</simpara>
</note>
<simpara>application.yml</simpara>
<programlisting language="yaml" linenumbering="unnumbered"># To disable Hystrix in Feign
feign:
hystrix:
enabled: false
# To set thread isolation to SEMAPHORE
hystrix:
command:
default:
execution:
isolation:
strategy: SEMAPHORE</programlisting>
</section>
<section xml:id="_creating_feign_clients_manually">
<title>Creating Feign Clients Manually</title>
<simpara>In some cases it might be necessary to customize your Feign Clients in a way that is not
possible using the methods above. In this case you can create Clients using the
<link xl:href="https://github.com/OpenFeign/feign/#basics">Feign Builder API</link>. Below is an example
which creates two Feign Clients with the same interface but configures each one with
a separate request interceptor.</simpara>
<programlisting language="java" linenumbering="unnumbered">@Import(FeignClientsConfiguration.class)
class FooController {
private FooClient fooClient;
private FooClient adminClient;
@Autowired
public FooController(
Decoder decoder, Encoder encoder, Client client) {
this.fooClient = Feign.builder().client(client)
.encoder(encoder)
.decoder(decoder)
.requestInterceptor(new BasicAuthRequestInterceptor("user", "user"))
.target(FooClient.class, "http://PROD-SVC");
this.adminClient = Feign.builder().client(client)
.encoder(encoder)
.decoder(decoder)
.requestInterceptor(new BasicAuthRequestInterceptor("admin", "admin"))
.target(FooClient.class, "http://PROD-SVC");
}
}</programlisting>
<note>
<simpara>In the above example <literal>FeignClientsConfiguration.class</literal> is the default configuration
provided by Spring Cloud Netflix.</simpara>
</note>
<note>
<simpara><literal>PROD-SVC</literal> is the name of the service the Clients will be making requests to.</simpara>
</note>
</section>
<section xml:id="spring-cloud-feign-hystrix">
<title>Feign Hystrix Support</title>
<simpara>If Hystrix is on the classpath and <literal>feign.hystrix.enabled=true</literal>, Feign will wrap all methods with a circuit breaker. Returning a <literal>com.netflix.hystrix.HystrixCommand</literal> is also available. This lets you use reactive patterns (with a call to <literal>.toObservable()</literal> or <literal>.observe()</literal> or asynchronous use (with a call to <literal>.queue()</literal>).</simpara>
<simpara>To disable Hystrix support on a per-client basis create a vanilla <literal>Feign.Builder</literal> with the "prototype" scope, e.g.:</simpara>
<programlisting language="java" linenumbering="unnumbered">@Configuration
public class FooConfiguration {
@Bean
@Scope("prototype")
public Feign.Builder feignBuilder() {
return Feign.builder();
}
}</programlisting>
<warning>
<simpara>Prior to the Spring Cloud Dalston release, if Hystrix was on the classpath Feign would have wrapped
all methods in a circuit breaker by default. This default behavior was changed in Spring Cloud Dalston in
favor for an opt-in approach.</simpara>
</warning>
</section>
<section xml:id="spring-cloud-feign-hystrix-fallback">
<title>Feign Hystrix Fallbacks</title>
<simpara>Hystrix supports the notion of a fallback: a default code path that is executed when they circuit is open or there is an error. To enable fallbacks for a given <literal>@FeignClient</literal> set the <literal>fallback</literal> attribute to the class name that implements the fallback. You also need to declare your implementation as a Spring bean.</simpara>
<programlisting language="java" linenumbering="unnumbered">@FeignClient(name = "hello", fallback = HystrixClientFallback.class)
protected interface HystrixClient {
@RequestMapping(method = RequestMethod.GET, value = "/hello")
Hello iFailSometimes();
}
static class HystrixClientFallback implements HystrixClient {
@Override
public Hello iFailSometimes() {
return new Hello("fallback");
}
}</programlisting>
<simpara>If one needs access to the cause that made the fallback trigger, one can use the <literal>fallbackFactory</literal> attribute inside <literal>@FeignClient</literal>.</simpara>
<programlisting language="java" linenumbering="unnumbered">@FeignClient(name = "hello", fallbackFactory = HystrixClientFallbackFactory.class)
protected interface HystrixClient {
@RequestMapping(method = RequestMethod.GET, value = "/hello")
Hello iFailSometimes();
}
@Component
static class HystrixClientFallbackFactory implements FallbackFactory&lt;HystrixClient&gt; {
@Override
public HystrixClient create(Throwable cause) {
return new HystrixClient() {
@Override
public Hello iFailSometimes() {
return new Hello("fallback; reason was: " + cause.getMessage());
}
};
}
}</programlisting>
<warning>
<simpara>There is a limitation with the implementation of fallbacks in Feign and how Hystrix fallbacks work. Fallbacks are currently not supported for methods that return <literal>com.netflix.hystrix.HystrixCommand</literal> and <literal>rx.Observable</literal>.</simpara>
</warning>
</section>
<section xml:id="_feign_and_literal_primary_literal">
<title>Feign and <literal>@Primary</literal></title>
<simpara>When using Feign with Hystrix fallbacks, there are multiple beans in the <literal>ApplicationContext</literal> of the same type. This will cause <literal>@Autowired</literal> to not work because there isn&#8217;t exactly one bean, or one marked as primary. To work around this, Spring Cloud Netflix marks all Feign instances as <literal>@Primary</literal>, so Spring Framework will know which bean to inject. In some cases, this may not be desirable. To turn off this behavior set the <literal>primary</literal> attribute of <literal>@FeignClient</literal> to false.</simpara>
<programlisting language="java" linenumbering="unnumbered">@FeignClient(name = "hello", primary = false)
public interface HelloClient {
// methods here
}</programlisting>
</section>
<section xml:id="spring-cloud-feign-inheritance">
<title>Feign Inheritance Support</title>
<simpara>Feign supports boilerplate apis via single-inheritance interfaces.
This allows grouping common operations into convenient base interfaces.</simpara>
<formalpara>
<title>UserService.java</title>
<para>
<programlisting language="java" linenumbering="unnumbered">public interface UserService {
@RequestMapping(method = RequestMethod.GET, value ="/users/{id}")
User getUser(@PathVariable("id") long id);
}</programlisting>
</para>
</formalpara>
<formalpara>
<title>UserResource.java</title>
<para>
<programlisting language="java" linenumbering="unnumbered">@RestController
public class UserResource implements UserService {
}</programlisting>
</para>
</formalpara>
<formalpara>
<title>UserClient.java</title>
<para>
<programlisting language="java" linenumbering="unnumbered">package project.user;
@FeignClient("users")
public interface UserClient extends UserService {
}</programlisting>
</para>
</formalpara>
<note>
<simpara>It is generally not advisable to share an interface between a
server and a client. It introduces tight coupling, and also actually
doesn&#8217;t work with Spring MVC in its current form (method parameter
mapping is not inherited).</simpara>
</note>
</section>
<section xml:id="_feign_request_response_compression">
<title>Feign request/response compression</title>
<simpara>You may consider enabling the request or response GZIP compression for your
Feign requests. You can do this by enabling one of the properties:</simpara>
<programlisting language="java" linenumbering="unnumbered">feign.compression.request.enabled=true
feign.compression.response.enabled=true</programlisting>
<simpara>Feign request compression gives you settings similar to what you may set for your web server:</simpara>
<programlisting language="java" linenumbering="unnumbered">feign.compression.request.enabled=true
feign.compression.request.mime-types=text/xml,application/xml,application/json
feign.compression.request.min-request-size=2048</programlisting>
<simpara>These properties allow you to be selective about the compressed media types and minimum request threshold length.</simpara>
</section>
<section xml:id="_feign_logging">
<title>Feign logging</title>
<simpara>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 <literal>DEBUG</literal> level.</simpara>
<formalpara>
<title>application.yml</title>
<para>
<programlisting language="yaml" linenumbering="unnumbered">logging.level.project.user.UserClient: DEBUG</programlisting>
</para>
</formalpara>
<simpara>The <literal>Logger.Level</literal> object that you may configure per client, tells Feign how much to log. Choices are:</simpara>
<itemizedlist>
<listitem>
<simpara><literal>NONE</literal>, No logging (<emphasis role="strong">DEFAULT</emphasis>).</simpara>
</listitem>
<listitem>
<simpara><literal>BASIC</literal>, Log only the request method and URL and the response status code and execution time.</simpara>
</listitem>
<listitem>
<simpara><literal>HEADERS</literal>, Log the basic information along with request and response headers.</simpara>
</listitem>
<listitem>
<simpara><literal>FULL</literal>, Log the headers, body, and metadata for both requests and responses.</simpara>
</listitem>
</itemizedlist>
<simpara>For example, the following would set the <literal>Logger.Level</literal> to <literal>FULL</literal>:</simpara>
<programlisting language="java" linenumbering="unnumbered">@Configuration
public class FooConfiguration {
@Bean
Logger.Level feignLoggerLevel() {
return Logger.Level.FULL;
}
}</programlisting>
</section>
</chapter>
<chapter xml:id="_external_configuration_archaius">
<title>External Configuration: Archaius</title>
<simpara><link xl:href="https://github.com/Netflix/archaius">Archaius</link> is the Netflix client side configuration library. It is the library used by all of the Netflix OSS components for configuration. Archaius is an extension of the <link xl:href="http://commons.apache.org/proper/commons-configuration">Apache Commons Configuration</link> project. It allows updates to configuration by either polling a source for changes or for a source to push changes to the client. Archaius uses Dynamic&lt;Type&gt;Property classes as handles to properties.</simpara>
<formalpara>
<title>Archaius Example</title>
<para>
<programlisting language="java" linenumbering="unnumbered">class ArchaiusTest {
DynamicStringProperty myprop = DynamicPropertyFactory
.getInstance()
.getStringProperty("my.prop");
void doSomething() {
OtherClass.someMethod(myprop.get());
}
}</programlisting>
</para>
</formalpara>
<simpara>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.</simpara>
</chapter>
<chapter xml:id="_router_and_filter_zuul">
<title>Router and Filter: Zuul</title>
<simpara>Routing in an integral part of a microservice architecture. For example, <literal>/</literal> may be mapped to your web application, <literal>/api/users</literal> is mapped to the user service and <literal>/api/shop</literal> is mapped to the shop service. <link xl:href="https://github.com/Netflix/zuul">Zuul</link> is a JVM based router and server side load balancer by Netflix.</simpara>
<simpara><link xl:href="http://www.slideshare.net/MikeyCohen1/edge-architecture-ieee-international-conference-on-cloud-engineering-32240146/27">Netflix uses Zuul</link> for the following:</simpara>
<itemizedlist>
<listitem>
<simpara>Authentication</simpara>
</listitem>
<listitem>
<simpara>Insights</simpara>
</listitem>
<listitem>
<simpara>Stress Testing</simpara>
</listitem>
<listitem>
<simpara>Canary Testing</simpara>
</listitem>
<listitem>
<simpara>Dynamic Routing</simpara>
</listitem>
<listitem>
<simpara>Service Migration</simpara>
</listitem>
<listitem>
<simpara>Load Shedding</simpara>
</listitem>
<listitem>
<simpara>Security</simpara>
</listitem>
<listitem>
<simpara>Static Response handling</simpara>
</listitem>
<listitem>
<simpara>Active/Active traffic management</simpara>
</listitem>
</itemizedlist>
<simpara>Zuul&#8217;s rule engine allows rules and filters to be written in essentially any JVM language, with built in support for Java and Groovy.</simpara>
<note>
<simpara>The configuration property <literal>zuul.max.host.connections</literal> has been replaced by two new properties, <literal>zuul.host.maxTotalConnections</literal> and <literal>zuul.host.maxPerRouteConnections</literal> which default to 200 and 20 respectively.</simpara>
</note>
<note>
<simpara>Default Hystrix isolation pattern (ExecutionIsolationStrategy) for all routes is SEMAPHORE. <literal>zuul.ribbonIsolationStrategy</literal> can be changed to THREAD if this isolation pattern is preferred.</simpara>
</note>
<section xml:id="netflix-zuul-starter">
<title>How to Include Zuul</title>
<simpara>To include Zuul in your project use the starter with group <literal>org.springframework.cloud</literal>
and artifact id <literal>spring-cloud-starter-netflix-zuul</literal>. See the <link xl:href="http://projects.spring.io/spring-cloud/">Spring Cloud Project page</link>
for details on setting up your build system with the current Spring Cloud Release Train.</simpara>
</section>
<section xml:id="netflix-zuul-reverse-proxy">
<title>Embedded Zuul Reverse Proxy</title>
<simpara>Spring Cloud has created an embedded Zuul proxy to ease the
development of a very common use case where a UI application wants to
proxy calls to one or more back end services. This feature is useful
for a user interface to proxy to the backend services it requires,
avoiding the need to manage CORS and authentication concerns
independently for all the backends.</simpara>
<simpara>To enable it, annotate a Spring Boot main class with
<literal>@EnableZuulProxy</literal>, and this forwards local calls to the appropriate
service. By convention, a service with the ID "users", will
receive requests from the proxy located at <literal>/users</literal> (with the prefix
stripped). The proxy uses Ribbon to locate an instance to forward to
via discovery, and all requests are executed in a
<link linkend="hystrix-fallbacks-for-routes">hystrix command</link>, so
failures will show up in Hystrix metrics, and once the circuit is open
the proxy will not try to contact the service.</simpara>
<note>
<simpara>the Zuul starter does not include a discovery client, so for
routes based on service IDs you need to provide one of those
on the classpath as well (e.g. Eureka is one choice).</simpara>
</note>
<simpara>To skip having a service automatically added, set
<literal>zuul.ignored-services</literal> to a list of service id patterns. If a service
matches a pattern that is ignored, but also included in the explicitly
configured routes map, then it will be unignored. Example:</simpara>
<formalpara>
<title>application.yml</title>
<para>
<programlisting language="yaml" linenumbering="unnumbered"> zuul:
ignoredServices: '*'
routes:
users: /myusers/**</programlisting>
</para>
</formalpara>
<simpara>In this example, all services are ignored <emphasis role="strong">except</emphasis> "users".</simpara>
<simpara>To augment or change
the proxy routes, you can add external configuration like the
following:</simpara>
<formalpara>
<title>application.yml</title>
<para>
<programlisting language="yaml" linenumbering="unnumbered"> zuul:
routes:
users: /myusers/**</programlisting>
</para>
</formalpara>
<simpara>This means that http calls to "/myusers" get forwarded to the "users"
service (for example "/myusers/101" is forwarded to "/101").</simpara>
<simpara>To get more fine-grained control over a route you can specify the path
and the serviceId independently:</simpara>
<formalpara>
<title>application.yml</title>
<para>
<programlisting language="yaml" linenumbering="unnumbered"> zuul:
routes:
users:
path: /myusers/**
serviceId: users_service</programlisting>
</para>
</formalpara>
<simpara>This means that http calls to "/myusers" get forwarded to the
"users_service" service. The route has to have a "path" which can be
specified as an ant-style pattern, so "/myusers/*" only matches one
level, but "/myusers/**" matches hierarchically.</simpara>
<simpara>The location of the backend can be specified as either a "serviceId"
(for a service from discovery) or a "url" (for a physical location), e.g.</simpara>
<formalpara>
<title>application.yml</title>
<para>
<programlisting language="yaml" linenumbering="unnumbered"> zuul:
routes:
users:
path: /myusers/**
url: http://example.com/users_service</programlisting>
</para>
</formalpara>
<simpara>These simple url-routes don&#8217;t get executed as a <literal>HystrixCommand</literal> nor do they loadbalance multiple URLs with Ribbon.
To achieve this, you can specify a <literal>serviceId</literal> with a static list of servers:</simpara>
<formalpara>
<title>application.yml</title>
<para>
<programlisting language="yaml" linenumbering="unnumbered">zuul:
routes:
echo:
path: /myusers/**
serviceId: myusers-service
stripPrefix: true
hystrix:
command:
myusers-service:
execution:
isolation:
thread:
timeoutInMilliseconds: ...
myusers-service:
ribbon:
NIWSServerListClassName: com.netflix.loadbalancer.ConfigurationBasedServerList
ListOfServers: http://example1.com,http://example2.com
ConnectTimeout: 1000
ReadTimeout: 3000
MaxTotalHttpConnections: 500
MaxConnectionsPerHost: 100</programlisting>
</para>
</formalpara>
<simpara>Another method is specifiying a service-route and configure a Ribbon client for the
serviceId (this requires disabling Eureka support in Ribbon:
see <link linkend="spring-cloud-ribbon-without-eureka">above for more information</link>), e.g.</simpara>
<formalpara>
<title>application.yml</title>
<para>
<programlisting language="yaml" linenumbering="unnumbered">zuul:
routes:
users:
path: /myusers/**
serviceId: users
ribbon:
eureka:
enabled: false
users:
ribbon:
listOfServers: example.com,google.com</programlisting>
</para>
</formalpara>
<simpara>You can provide convention between serviceId and routes using
regexmapper. It uses regular expression named groups to extract
variables from serviceId and inject them into a route pattern.</simpara>
<formalpara>
<title>ApplicationConfiguration.java</title>
<para>
<programlisting language="java" linenumbering="unnumbered">@Bean
public PatternServiceRouteMapper serviceRouteMapper() {
return new PatternServiceRouteMapper(
"(?&lt;name&gt;^.+)-(?&lt;version&gt;v.+$)",
"${version}/${name}");
}</programlisting>
</para>
</formalpara>
<simpara>This means that a serviceId "myusers-v1" will be mapped to route
"/v1/myusers/**". Any regular expression is accepted but all named
groups must be present in both servicePattern and routePattern. If
servicePattern does not match a serviceId, the default behavior is
used. In the example above, a serviceId "myusers" will be mapped to route
"/myusers/**" (no version detected) This feature is disabled by
default and only applies to discovered services.</simpara>
<simpara>To add a prefix to all mappings, set <literal>zuul.prefix</literal> to a value, such as
<literal>/api</literal>. The proxy prefix is stripped from the request before the
request is forwarded by default (switch this behaviour off with
<literal>zuul.stripPrefix=false</literal>). You can also switch off the stripping of
the service-specific prefix from individual routes, e.g.</simpara>
<formalpara>
<title>application.yml</title>
<para>
<programlisting language="yaml" linenumbering="unnumbered"> zuul:
routes:
users:
path: /myusers/**
stripPrefix: false</programlisting>
</para>
</formalpara>
<note>
<simpara><literal>zuul.stripPrefix</literal> only applies to the prefix set in <literal>zuul.prefix</literal>. It does not have any effect on prefixes
defined within a given route&#8217;s <literal>path</literal>.</simpara>
</note>
<simpara>In this example, requests to "/myusers/101" will be forwarded to "/myusers/101" on the "users" service.</simpara>
<simpara>The <literal>zuul.routes</literal> entries actually bind to an object of type <literal>ZuulProperties</literal>. If you
look at the properties of that object you will see that it also has a "retryable" flag.
Set that flag to "true" to have the Ribbon client automatically retry failed requests
(and if you need to you can modify the parameters of the retry operations using
the Ribbon client configuration).</simpara>
<simpara>The <literal>X-Forwarded-Host</literal> header is added to the forwarded requests by
default. To turn it off set <literal>zuul.addProxyHeaders = false</literal>. The
prefix path is stripped by default, and the request to the backend
picks up a header "X-Forwarded-Prefix" ("/myusers" in the examples
above).</simpara>
<simpara>An application with <literal>@EnableZuulProxy</literal> could act as a standalone
server if you set a default route ("/"), for example <literal>zuul.route.home:
/</literal> would route all traffic (i.e. "/**") to the "home" service.</simpara>
<simpara>If more fine-grained ignoring is needed, you can specify specific patterns to ignore.
These patterns are evaluated at the start of the route location process, which
means prefixes should be included in the pattern to warrant a match. Ignored patterns
span all services and supersede any other route specification.</simpara>
<formalpara>
<title>application.yml</title>
<para>
<programlisting language="yaml" linenumbering="unnumbered"> zuul:
ignoredPatterns: /**/admin/**
routes:
users: /myusers/**</programlisting>
</para>
</formalpara>
<simpara>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.</simpara>
<warning>
<simpara>If you need your routes to have their order preserved you need to use a YAML
file as the ordering will be lost using a properties file. For example:</simpara>
</warning>
<formalpara>
<title>application.yml</title>
<para>
<programlisting language="yaml" linenumbering="unnumbered"> zuul:
routes:
users:
path: /myusers/**
legacy:
path: /**</programlisting>
</para>
</formalpara>
<simpara>If you were to use a properties file, the <literal>legacy</literal> path may end up in front of the <literal>users</literal>
path rendering the <literal>users</literal> path unreachable.</simpara>
</section>
<section xml:id="_zuul_http_client">
<title>Zuul Http Client</title>
<simpara>The default HTTP client used by zuul is now backed by the Apache HTTP Client instead of the
deprecated Ribbon <literal>RestClient</literal>. To use <literal>RestClient</literal> or to use the <literal>okhttp3.OkHttpClient</literal> set
<literal>ribbon.restclient.enabled=true</literal> or <literal>ribbon.okhttp.enabled=true</literal> respectively. If you would
like to customize the Apache HTTP client or the OK HTTP client provide a bean of type
<literal>ClosableHttpClient</literal> or <literal>OkHttpClient</literal>.</simpara>
</section>
<section xml:id="_cookies_and_sensitive_headers">
<title>Cookies and Sensitive Headers</title>
<simpara>It&#8217;s OK to share headers between services in the same system, but you
probably don&#8217;t want sensitive headers leaking downstream into external
servers. You can specify a list of ignored headers as part of the
route configuration. Cookies play a special role because they have
well-defined semantics in browsers, and they are always to be treated
as sensitive. If the consumer of your proxy is a browser, then cookies
for downstream services also cause problems for the user because they
all get jumbled up (all downstream services look like they come from
the same place).</simpara>
<simpara>If you are careful with the design of your services, for example if
only one of the downstream services sets cookies, then you might be
able to let them flow from the backend all the way up to the
caller. Also, if your proxy sets cookies and all your back end
services are part of the same system, it can be natural to simply
share them (and for instance use Spring Session to link them up to some
shared state). Other than that, any cookies that get set by downstream
services are likely to be not very useful to the caller, so it is
recommended that you make (at least) "Set-Cookie" and "Cookie" into
sensitive headers for routes that are not part of your domain. Even
for routes that <emphasis role="strong">are</emphasis> part of your domain, try to think carefully
about what it means before allowing cookies to flow between them and
the proxy.</simpara>
<simpara>The sensitive headers can be configured as a comma-separated list per
route, e.g.</simpara>
<formalpara>
<title>application.yml</title>
<para>
<programlisting language="yaml" linenumbering="unnumbered"> zuul:
routes:
users:
path: /myusers/**
sensitiveHeaders: Cookie,Set-Cookie,Authorization
url: https://downstream</programlisting>
</para>
</formalpara>
<note>
<simpara>this is the default value for <literal>sensitiveHeaders</literal>, so you don&#8217;t
need to set it unless you want it to be different. N.B. this is new in
Spring Cloud Netflix 1.1 (in 1.0 the user had no control over headers
and all cookies flow in both directions).</simpara>
</note>
<simpara>The <literal>sensitiveHeaders</literal> are a blacklist and the default is not empty,
so to make Zuul send all headers (except the "ignored" ones) you would
have to explicitly set it to the empty list. This is necessary if you
want to pass cookie or authorization headers to your back end. Example:</simpara>
<formalpara>
<title>application.yml</title>
<para>
<programlisting language="yaml" linenumbering="unnumbered"> zuul:
routes:
users:
path: /myusers/**
sensitiveHeaders:
url: https://downstream</programlisting>
</para>
</formalpara>
<simpara>Sensitive headers can also be set globally by setting <literal>zuul.sensitiveHeaders</literal>. If <literal>sensitiveHeaders</literal> is set on a route, this will override the global <literal>sensitiveHeaders</literal> setting.</simpara>
</section>
<section xml:id="_ignored_headers">
<title>Ignored Headers</title>
<simpara>In addition to the per-route sensitive headers, you can set a global
value for <literal>zuul.ignoredHeaders</literal> for values that should be discarded
(both request and response) during interactions with downstream
services. By default these are empty, if Spring Security is not on the
classpath, and otherwise they are initialized to a set of well-known
"security" headers (e.g. involving caching) as specified by Spring
Security. The assumption in this case is that the downstream services
might add these headers too, and we want the values from the proxy.
To not discard these well known security headers in case Spring Security is on the classpath you can set <literal>zuul.ignoreSecurityHeaders</literal> to <literal>false</literal>. This can be useful if you disabled the HTTP Security response headers in Spring Security and want the values provided by downstream services</simpara>
</section>
<section xml:id="_management_endpoints">
<title>Management Endpoints</title>
<simpara>If you are using <literal>@EnableZuulProxy</literal> with the Spring Boot Actuator you
will enable (by default) two additional endpoints:</simpara>
<itemizedlist>
<listitem>
<simpara>Routes</simpara>
</listitem>
<listitem>
<simpara>Filters</simpara>
</listitem>
</itemizedlist>
<section xml:id="_routes_endpoint">
<title>Routes Endpoint</title>
<simpara>A GET to the routes endpoint at <literal>/routes</literal> will return a list of the mapped
routes:</simpara>
<formalpara>
<title>GET /routes</title>
<para>
<programlisting language="json" linenumbering="unnumbered">{
/stores/**: "http://localhost:8081"
}</programlisting>
</para>
</formalpara>
<simpara>Additional route details can be requested by adding the <literal>?format=details</literal> query
string to <literal>/routes</literal>. This will produce the following output:</simpara>
<formalpara>
<title>GET /routes/details</title>
<para>
<programlisting language="json" linenumbering="unnumbered">{
"/stores/**": {
"id": "stores",
"fullPath": "/stores/**",
"location": "http://localhost:8081",
"path": "/**",
"prefix": "/stores",
"retryable": false,
"customSensitiveHeaders": false,
"prefixStripped": true
}
}</programlisting>
</para>
</formalpara>
<simpara>A POST will force a refresh of the existing routes (e.g. in
case there have been changes in the service catalog). You can disable
this endpoint by setting <literal>endpoints.routes.enabled</literal> to <literal>false</literal>.</simpara>
<note>
<simpara>the routes should respond automatically to changes in the
service catalog, but the POST to /routes is a way to force the change
to happen immediately.</simpara>
</note>
</section>
<section xml:id="_filters_endpoint">
<title>Filters Endpoint</title>
<simpara>A GET to the filters endpoint at <literal>/filters</literal> will return a map of Zuul
filters by type. For each filter type in the map, you will find a list
of all the filters of that type, along with their details.</simpara>
</section>
</section>
<section xml:id="_strangulation_patterns_and_local_forwards">
<title>Strangulation Patterns and Local Forwards</title>
<simpara>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.</simpara>
<simpara>Example configuration:</simpara>
<formalpara>
<title>application.yml</title>
<para>
<programlisting language="yaml" linenumbering="unnumbered"> 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</programlisting>
</para>
</formalpara>
<simpara>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
<literal>/first/**</literal> have been extracted into a new service with an external
URL. And paths in <literal>/second/**</literal> are forwarded so they can be handled
locally, e.g. with a normal Spring <literal>@RequestMapping</literal>. Paths in
<literal>/third/**</literal> are also forwarded, but with a different prefix
(i.e. <literal>/third/foo</literal> is forwarded to <literal>/3rd/foo</literal>).</simpara>
<note>
<simpara>The ignored patterns aren&#8217;t completely ignored, they just
aren&#8217;t handled by the proxy (so they are also effectively forwarded
locally).</simpara>
</note>
</section>
<section xml:id="_uploading_files_through_zuul">
<title>Uploading Files through Zuul</title>
<simpara>If you <literal>@EnableZuulProxy</literal> you can use the proxy paths to
upload files and it should just work as long as the files
are small. For large files there is an alternative path
which bypasses the Spring <literal>DispatcherServlet</literal> (to
avoid multipart processing) in "/zuul/*". I.e. if
<literal>zuul.routes.customers=/customers/**</literal> then you can
POST large files to "/zuul/customers/*". The servlet
path is externalized via <literal>zuul.servletPath</literal>. Extremely
large files will also require elevated timeout settings
if the proxy route takes you through a Ribbon load
balancer, e.g.</simpara>
<formalpara>
<title>application.yml</title>
<para>
<programlisting language="yaml" linenumbering="unnumbered">hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds: 60000
ribbon:
ConnectTimeout: 3000
ReadTimeout: 60000</programlisting>
</para>
</formalpara>
<simpara>Note that for streaming to work with large files, you need to use chunked encoding in the request (which some browsers
do not do by default). E.g. on the command line:</simpara>
<screen>$ curl -v -H "Transfer-Encoding: chunked" \
-F "file=@mylarge.iso" localhost:9999/zuul/simple/file</screen>
</section>
<section xml:id="_query_string_encoding">
<title>Query String Encoding</title>
<simpara>When processing the incoming request, query params are decoded so they can be available for possible modifications in
Zuul filters. They are then re-encoded when building the backend request in the route filters. The result
can be different than the original input if it was encoded using Javascript&#8217;s <literal>encodeURIComponent()</literal> method for example.
While this causes no issues in most cases, some web servers can be picky with the encoding of complex query string.</simpara>
<simpara>To force the original encoding of the query string, it is possible to pass a special flag to <literal>ZuulProperties</literal> so
that the query string is taken as is with the <literal>HttpServletRequest::getQueryString</literal> method :</simpara>
<formalpara>
<title>application.yml</title>
<para>
<programlisting language="yaml" linenumbering="unnumbered"> zuul:
forceOriginalQueryStringEncoding: true</programlisting>
</para>
</formalpara>
<simpara><emphasis role="strong">Note:</emphasis> This special flag only works with <literal>SimpleHostRoutingFilter</literal> and you loose the ability to easily override
query parameters with <literal>RequestContext.getCurrentContext().setRequestQueryParams(someOverriddenParameters)</literal> since
the query string is now fetched directly on the original <literal>HttpServletRequest</literal>.</simpara>
</section>
<section xml:id="_plain_embedded_zuul">
<title>Plain Embedded Zuul</title>
<simpara>You can also run a Zuul server without the proxying, or switch on parts of the proxying platform selectively, if you
use <literal>@EnableZuulServer</literal> (instead of <literal>@EnableZuulProxy</literal>). Any beans that you add to the application of type <literal>ZuulFilter</literal>
will be installed automatically, as they are with <literal>@EnableZuulProxy</literal>, but without any of the proxy filters being added
automatically.</simpara>
<simpara>In this case the routes into the Zuul server are still specified by
configuring "zuul.routes.*", but there is no service
discovery and no proxying, so the "serviceId" and "url" settings are
ignored. For example:</simpara>
<formalpara>
<title>application.yml</title>
<para>
<programlisting language="yaml" linenumbering="unnumbered"> zuul:
routes:
api: /api/**</programlisting>
</para>
</formalpara>
<simpara>maps all paths in "/api/**" to the Zuul filter chain.</simpara>
</section>
<section xml:id="_disable_zuul_filters">
<title>Disable Zuul Filters</title>
<simpara>Zuul for Spring Cloud comes with a number of <literal>ZuulFilter</literal> beans enabled by default
in both proxy and server mode. See <link xl:href="https://github.com/spring-cloud/spring-cloud-netflix/tree/master/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/zuul/filters">the zuul filters package</link> for the
possible filters that are enabled. If you want to disable one, simply set
<literal>zuul.&lt;SimpleClassName&gt;.&lt;filterType&gt;.disable=true</literal>. By convention, the package after
<literal>filters</literal> is the Zuul filter type. For example to disable
<literal>org.springframework.cloud.netflix.zuul.filters.post.SendResponseFilter</literal> set
<literal>zuul.SendResponseFilter.post.disable=true</literal>.</simpara>
</section>
<section xml:id="hystrix-fallbacks-for-routes">
<title>Providing Hystrix Fallbacks For Routes</title>
<simpara>When a circuit for a given route in Zuul is tripped you can provide a fallback response
by creating a bean of type <literal>ZuulFallbackProvider</literal>. Within this bean you need to specify
the route ID the fallback is for and provide a <literal>ClientHttpResponse</literal> to return
as a fallback. Here is a very simple <literal>ZuulFallbackProvider</literal> implementation.</simpara>
<programlisting language="java" linenumbering="unnumbered">class MyFallbackProvider implements ZuulFallbackProvider {
@Override
public String getRoute() {
return "customers";
}
@Override
public ClientHttpResponse fallbackResponse() {
return new ClientHttpResponse() {
@Override
public HttpStatus getStatusCode() throws IOException {
return HttpStatus.OK;
}
@Override
public int getRawStatusCode() throws IOException {
return 200;
}
@Override
public String getStatusText() throws IOException {
return "OK";
}
@Override
public void close() {
}
@Override
public InputStream getBody() throws IOException {
return new ByteArrayInputStream("fallback".getBytes());
}
@Override
public HttpHeaders getHeaders() {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
return headers;
}
};
}
}</programlisting>
<simpara>And here is what the route configuration would look like.</simpara>
<programlisting language="yaml" linenumbering="unnumbered">zuul:
routes:
customers: /customers/**</programlisting>
<simpara>If you would like to provide a default fallback for all routes than you can create a bean of
type <literal>ZuulFallbackProvider</literal> and have the <literal>getRoute</literal> method return <literal>*</literal> or <literal>null</literal>.</simpara>
<programlisting language="java" linenumbering="unnumbered">class MyFallbackProvider implements ZuulFallbackProvider {
@Override
public String getRoute() {
return "*";
}
@Override
public ClientHttpResponse fallbackResponse() {
return new ClientHttpResponse() {
@Override
public HttpStatus getStatusCode() throws IOException {
return HttpStatus.OK;
}
@Override
public int getRawStatusCode() throws IOException {
return 200;
}
@Override
public String getStatusText() throws IOException {
return "OK";
}
@Override
public void close() {
}
@Override
public InputStream getBody() throws IOException {
return new ByteArrayInputStream("fallback".getBytes());
}
@Override
public HttpHeaders getHeaders() {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
return headers;
}
};
}
}</programlisting>
<simpara>If you would like to choose the response based on the cause of the failure use <literal>FallbackProvider</literal> which will replace <literal>ZuulFallbackProvder</literal> in future versions.</simpara>
<programlisting language="java" linenumbering="unnumbered">class MyFallbackProvider implements FallbackProvider {
@Override
public String getRoute() {
return "*";
}
@Override
public ClientHttpResponse fallbackResponse(final Throwable cause) {
if (cause instanceof HystrixTimeoutException) {
return response(HttpStatus.GATEWAY_TIMEOUT);
} else {
return fallbackResponse();
}
}
@Override
public ClientHttpResponse fallbackResponse() {
return response(HttpStatus.INTERNAL_SERVER_ERROR);
}
private ClientHttpResponse response(final HttpStatus status) {
return new ClientHttpResponse() {
@Override
public HttpStatus getStatusCode() throws IOException {
return status;
}
@Override
public int getRawStatusCode() throws IOException {
return status.value();
}
@Override
public String getStatusText() throws IOException {
return status.getReasonPhrase();
}
@Override
public void close() {
}
@Override
public InputStream getBody() throws IOException {
return new ByteArrayInputStream("fallback".getBytes());
}
@Override
public HttpHeaders getHeaders() {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
return headers;
}
};
}
}</programlisting>
</section>
<section xml:id="_zuul_timeouts">
<title>Zuul Timeouts</title>
<simpara>If you want to configure the socket timeouts and read timeouts for requests proxied through
Zuul there are two options based on your configuration.</simpara>
<simpara>If Zuul is using service discovery then you need to configure these timeouts via Ribbon properties,
<literal>ribbon.ReadTimeout</literal> and <literal>ribbon.SocketTimeout</literal>.</simpara>
<simpara>If you have configured Zuul routes by specifying URLs then you will need to use
<literal>zuul.host.connect-timeout-millis</literal> and <literal>zuul.host.socket-timeout-millis</literal>.</simpara>
</section>
<section xml:id="zuul-redirect-location-rewrite">
<title>Rewriting <literal>Location</literal> header</title>
<simpara>If Zuul is fronting a web application then there may be a need to re-write the <literal>Location</literal> header when the web application redirects through a http status code of 3XX, otherwise the browser will end up redirecting to the web application&#8217;s url instead of the Zuul url.
A <literal>LocationRewriteFilter</literal> Zuul filter can be configured to re-write the Location header to the Zuul&#8217;s url, it also adds back the stripped global and route specific prefixes. The filter can be added the following way via a Spring Configuration file:</simpara>
<programlisting language="java" linenumbering="unnumbered">import org.springframework.cloud.netflix.zuul.filters.post.LocationRewriteFilter;
...
@Configuration
@EnableZuulProxy
public class ZuulConfig {
@Bean
public LocationRewriteFilter locationRewriteFilter() {
return new LocationRewriteFilter();
}
}</programlisting>
<warning>
<simpara>Use this filter with caution though, the filter acts on the <literal>Location</literal> header of ALL 3XX response codes which may not be appropriate in all scenarios, say if the user is redirecting to an external URL.</simpara>
</warning>
</section>
<section xml:id="zuul-developer-guide">
<title>Zuul Developer Guide</title>
<simpara>For a general overview of how Zuul works, please see <link xl:href="https://github.com/Netflix/zuul/wiki/How-it-Works">the Zuul Wiki</link>.</simpara>
<section xml:id="_the_zuul_servlet">
<title>The Zuul Servlet</title>
<simpara>Zuul is implemented as a Servlet. For the general cases, Zuul is embedded into the Spring Dispatch mechanism. This allows Spring MVC to be in control of the routing. In this case, Zuul is configured to buffer requests. If there is a need to go through Zuul without buffering requests (e.g. for large file uploads), the Servlet is also installed outside of the Spring Dispatcher. By default, this is located at <literal>/zuul</literal>. This path can be changed with the <literal>zuul.servlet-path</literal> property.</simpara>
</section>
<section xml:id="_zuul_requestcontext">
<title>Zuul RequestContext</title>
<simpara>To pass information between filters, Zuul uses a <link xl:href="https://github.com/Netflix/zuul/blob/1.x/zuul-core/src/main/java/com/netflix/zuul/context/RequestContext.java"><literal>RequestContext</literal></link>. Its data is held in a <literal>ThreadLocal</literal> specific to each request. Information about where to route requests, errors and the actual <literal>HttpServletRequest</literal> and <literal>HttpServletResponse</literal> are stored there. The <literal>RequestContext</literal> extends <literal>ConcurrentHashMap</literal>, so anything can be stored in the context. <link xl:href="https://github.com/spring-cloud/spring-cloud-netflix/blob/master/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/zuul/filters/support/FilterConstants.java"><literal>FilterConstants</literal></link> contains the keys that are used by the filters installed by Spring Cloud Netflix (more on these later).</simpara>
</section>
<section xml:id="__literal_enablezuulproxy_literal_vs_literal_enablezuulserver_literal">
<title><literal>@EnableZuulProxy</literal> vs. <literal>@EnableZuulServer</literal></title>
<simpara>Spring Cloud Netflix installs a number of filters based on which annotation was used to enable Zuul. <literal>@EnableZuulProxy</literal> is a superset of <literal>@EnableZuulServer</literal>. In other words, <literal>@EnableZuulProxy</literal> contains all filters installed by <literal>@EnableZuulServer</literal>. The additional filters in the "proxy" enable routing functionality. If you want a "blank" Zuul, you should use <literal>@EnableZuulServer</literal>.</simpara>
</section>
<section xml:id="__literal_enablezuulserver_literal_filters">
<title><literal>@EnableZuulServer</literal> Filters</title>
<simpara>Creates a <literal>SimpleRouteLocator</literal> that loads route definitions from Spring Boot configuration files.</simpara>
<simpara>The following filters are installed (as normal Spring Beans):</simpara>
<simpara>Pre filters:</simpara>
<itemizedlist>
<listitem>
<simpara><literal>ServletDetectionFilter</literal>: Detects if the request is through the Spring Dispatcher. Sets boolean with key <literal>FilterConstants.IS_DISPATCHER_SERVLET_REQUEST_KEY</literal>.</simpara>
</listitem>
<listitem>
<simpara><literal>FormBodyWrapperFilter</literal>: Parses form data and reencodes it for downstream requests.</simpara>
</listitem>
<listitem>
<simpara><literal>DebugFilter</literal>: if the <literal>debug</literal> request parameter is set, this filter sets <literal>RequestContext.setDebugRouting()</literal> and <literal>RequestContext.setDebugRequest()</literal> to true.</simpara>
</listitem>
</itemizedlist>
<simpara>Route filters:</simpara>
<itemizedlist>
<listitem>
<simpara><literal>SendForwardFilter</literal>: This filter forwards requests using the Servlet <literal>RequestDispatcher</literal>. The forwarding location is stored in the <literal>RequestContext</literal> attribute <literal>FilterConstants.FORWARD_TO_KEY</literal>. This is useful for forwarding to endpoints in the current application.</simpara>
</listitem>
</itemizedlist>
<simpara>Post filters:</simpara>
<itemizedlist>
<listitem>
<simpara><literal>SendResponseFilter</literal>: Writes responses from proxied requests to the current response.</simpara>
</listitem>
</itemizedlist>
<simpara>Error filters:</simpara>
<itemizedlist>
<listitem>
<simpara><literal>SendErrorFilter</literal>: Forwards to /error (by default) if <literal>RequestContext.getThrowable()</literal> is not null. The default forwarding path (<literal>/error</literal>) can be changed by setting the <literal>error.path</literal> property.</simpara>
</listitem>
</itemizedlist>
</section>
<section xml:id="__literal_enablezuulproxy_literal_filters">
<title><literal>@EnableZuulProxy</literal> Filters</title>
<simpara>Creates a <literal>DiscoveryClientRouteLocator</literal> that loads route definitions from a <literal>DiscoveryClient</literal> (like Eureka), as well as from properties. A route is created for each <literal>serviceId</literal> from the <literal>DiscoveryClient</literal>. As new services are added, the routes will be refreshed.</simpara>
<simpara>In addition to the filters described above, the following filters are installed (as normal Spring Beans):</simpara>
<simpara>Pre filters:</simpara>
<itemizedlist>
<listitem>
<simpara><literal>PreDecorationFilter</literal>: This filter determines where and how to route based on the supplied <literal>RouteLocator</literal>. It also sets various proxy-related headers for downstream requests.</simpara>
</listitem>
</itemizedlist>
<simpara>Route filters:</simpara>
<itemizedlist>
<listitem>
<simpara><literal>RibbonRoutingFilter</literal>: This filter uses Ribbon, Hystrix and pluggable HTTP clients to send requests. Service ids are found in the <literal>RequestContext</literal> attribute <literal>FilterConstants.SERVICE_ID_KEY</literal>. This filter can use different HTTP clients. They are:</simpara>
<itemizedlist>
<listitem>
<simpara>Apache <literal>HttpClient</literal>. This is the default client.</simpara>
</listitem>
<listitem>
<simpara>Squareup <literal>OkHttpClient</literal> v3. This is enabled by having the <literal>com.squareup.okhttp3:okhttp</literal> library on the classpath and setting <literal>ribbon.okhttp.enabled=true</literal>.</simpara>
</listitem>
<listitem>
<simpara>Netflix Ribbon HTTP client. This is enabled by setting <literal>ribbon.restclient.enabled=true</literal>. This client has limitations, such as it doesn&#8217;t support the PATCH method, but also has built-in retry.</simpara>
</listitem>
</itemizedlist>
</listitem>
<listitem>
<simpara><literal>SimpleHostRoutingFilter</literal>: This filter sends requests to predetermined URLs via an Apache HttpClient. URLs are found in <literal>RequestContext.getRouteHost()</literal>.</simpara>
</listitem>
</itemizedlist>
</section>
<section xml:id="_custom_zuul_filter_examples">
<title>Custom Zuul Filter examples</title>
<simpara>Most of the following "How to Write" examples below are included <link xl:href="https://github.com/spring-cloud-samples/sample-zuul-filters">Sample Zuul Filters</link> project. There are also examples of manipulating the request or response body in that repository.</simpara>
</section>
<section xml:id="_how_to_write_a_pre_filter">
<title>How to Write a Pre Filter</title>
<simpara>Pre filters are used to set up data in the <literal>RequestContext</literal> for use in filters downstream. The main use case is to set information required for route filters.</simpara>
<programlisting language="java" linenumbering="unnumbered">public class QueryParamPreFilter extends ZuulFilter {
@Override
public int filterOrder() {
return PRE_DECORATION_FILTER_ORDER - 1; // run before PreDecoration
}
@Override
public String filterType() {
return PRE_TYPE;
}
@Override
public boolean shouldFilter() {
RequestContext ctx = RequestContext.getCurrentContext();
return !ctx.containsKey(FORWARD_TO_KEY) // a filter has already forwarded
&amp;&amp; !ctx.containsKey(SERVICE_ID_KEY); // a filter has already determined serviceId
}
@Override
public Object run() {
RequestContext ctx = RequestContext.getCurrentContext();
HttpServletRequest request = ctx.getRequest();
if (request.getParameter("foo") != null) {
// put the serviceId in `RequestContext`
ctx.put(SERVICE_ID_KEY, request.getParameter("foo"));
}
return null;
}
}</programlisting>
<simpara>The filter above populates <literal>SERVICE_ID_KEY</literal> from the <literal>foo</literal> request parameter. In reality, it&#8217;s not a good idea to do that kind of direct mapping, but the service id should be looked up from the value of <literal>foo</literal> instead.</simpara>
<simpara>Now that <literal>SERVICE_ID_KEY</literal> is populated, <literal>PreDecorationFilter</literal> won&#8217;t run and <literal>RibbonRoutingFilter</literal> will. If you wanted to route to a full URL instead, call <literal>ctx.setRouteHost(url)</literal> instead.</simpara>
<simpara>To modify the path that routing filters will forward to, set the <literal>REQUEST_URI_KEY</literal>.</simpara>
</section>
<section xml:id="_how_to_write_a_route_filter">
<title>How to Write a Route Filter</title>
<simpara>Route filters are run after pre filters and are used to make requests to other services. Much of the work here is to translate request and response data to and from the client required model.</simpara>
<programlisting language="java" linenumbering="unnumbered">public class OkHttpRoutingFilter extends ZuulFilter {
@Autowired
private ProxyRequestHelper helper;
@Override
public String filterType() {
return ROUTE_TYPE;
}
@Override
public int filterOrder() {
return SIMPLE_HOST_ROUTING_FILTER_ORDER - 1;
}
@Override
public boolean shouldFilter() {
return RequestContext.getCurrentContext().getRouteHost() != null
&amp;&amp; RequestContext.getCurrentContext().sendZuulResponse();
}
@Override
public Object run() {
OkHttpClient httpClient = new OkHttpClient.Builder()
// customize
.build();
RequestContext context = RequestContext.getCurrentContext();
HttpServletRequest request = context.getRequest();
String method = request.getMethod();
String uri = this.helper.buildZuulRequestURI(request);
Headers.Builder headers = new Headers.Builder();
Enumeration&lt;String&gt; headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
String name = headerNames.nextElement();
Enumeration&lt;String&gt; values = request.getHeaders(name);
while (values.hasMoreElements()) {
String value = values.nextElement();
headers.add(name, value);
}
}
InputStream inputStream = request.getInputStream();
RequestBody requestBody = null;
if (inputStream != null &amp;&amp; HttpMethod.permitsRequestBody(method)) {
MediaType mediaType = null;
if (headers.get("Content-Type") != null) {
mediaType = MediaType.parse(headers.get("Content-Type"));
}
requestBody = RequestBody.create(mediaType, StreamUtils.copyToByteArray(inputStream));
}
Request.Builder builder = new Request.Builder()
.headers(headers.build())
.url(uri)
.method(method, requestBody);
Response response = httpClient.newCall(builder.build()).execute();
LinkedMultiValueMap&lt;String, String&gt; responseHeaders = new LinkedMultiValueMap&lt;&gt;();
for (Map.Entry&lt;String, List&lt;String&gt;&gt; entry : response.headers().toMultimap().entrySet()) {
responseHeaders.put(entry.getKey(), entry.getValue());
}
this.helper.setResponse(response.code(), response.body().byteStream(),
responseHeaders);
context.setRouteHost(null); // prevent SimpleHostRoutingFilter from running
return null;
}
}</programlisting>
<simpara>The above filter translates Servlet request information into OkHttp3 request information, executes an HTTP request, then translates OkHttp3 reponse information to the Servlet response. WARNING: this filter might have bugs and not function correctly.</simpara>
</section>
<section xml:id="_how_to_write_a_post_filter">
<title>How to Write a Post Filter</title>
<simpara>Post filters typically manipulate the response. In the filter below, we add a random <literal>UUID</literal> as the <literal>X-Foo</literal> header. Other manipulations, such as transforming the response body, are much more complex and compute-intensive.</simpara>
<programlisting language="java" linenumbering="unnumbered">public class AddResponseHeaderFilter extends ZuulFilter {
@Override
public String filterType() {
return POST_TYPE;
}
@Override
public int filterOrder() {
return SEND_RESPONSE_FILTER_ORDER - 1;
}
@Override
public boolean shouldFilter() {
return true;
}
@Override
public Object run() {
RequestContext context = RequestContext.getCurrentContext();
HttpServletResponse servletResponse = context.getResponse();
servletResponse.addHeader("X-Foo", UUID.randomUUID().toString());
return null;
}
}</programlisting>
</section>
<section xml:id="_how_zuul_errors_work">
<title>How Zuul Errors Work</title>
<simpara>If an exception is thrown during any portion of the Zuul filter lifecycle, the error filters are executed. The <literal>SendErrorFilter</literal> is only run if <literal>RequestContext.getThrowable()</literal> is not <literal>null</literal>. It then sets specific <literal>javax.servlet.error.*</literal> attributes in the request and forwards the request to the Spring Boot error page.</simpara>
</section>
<section xml:id="_zuul_eager_application_context_loading">
<title>Zuul Eager Application Context Loading</title>
<simpara>Zuul internally uses Ribbon for calling the remote url&#8217;s and Ribbon clients are by default lazily loaded up by Spring Cloud on first call.
This behavior can be changed for Zuul using the following configuration and will result in the child Ribbon related Application contexts being eagerly loaded up at application startup time.</simpara>
<formalpara>
<title>application.yml</title>
<para>
<screen>zuul:
ribbon:
eager-load:
enabled: true</screen>
</para>
</formalpara>
</section>
</section>
</chapter>
<chapter xml:id="_polyglot_support_with_sidecar">
<title>Polyglot support with Sidecar</title>
<simpara>Do you have non-jvm languages you want to take advantage of Eureka, Ribbon and
Config Server? The Spring Cloud Netflix Sidecar was inspired by
<link xl:href="https://github.com/Netflix/Prana">Netflix Prana</link>. It includes a simple http api
to get all of the instances (ie host and port) for a given service. You can
also proxy service calls through an embedded Zuul proxy which gets its route
entries from Eureka. The Spring Cloud Config Server can be accessed directly
via host lookup or through the Zuul Proxy. The non-jvm app should implement
a health check so the Sidecar can report to eureka if the app is up or down.</simpara>
<simpara>To include Sidecar in your project use the dependency with group <literal>org.springframework.cloud</literal>
and artifact id <literal>spring-cloud-netflix-sidecar</literal>.</simpara>
<simpara>To enable the Sidecar, create a Spring Boot application with <literal>@EnableSidecar</literal>.
This annotation includes <literal>@EnableCircuitBreaker</literal>, <literal>@EnableDiscoveryClient</literal>,
and <literal>@EnableZuulProxy</literal>. Run the resulting application on the same host as the
non-jvm application.</simpara>
<simpara>To configure the side car add <literal>sidecar.port</literal> and <literal>sidecar.health-uri</literal> to <literal>application.yml</literal>.
The <literal>sidecar.port</literal> property is the port the non-jvm app is listening on. This
is so the Sidecar can properly register the app with Eureka. The <literal>sidecar.health-uri</literal>
is a uri accessible on the non-jvm app that mimicks a Spring Boot health
indicator. It should return a json document like the following:</simpara>
<formalpara>
<title>health-uri-document</title>
<para>
<programlisting language="json" linenumbering="unnumbered">{
"status":"UP"
}</programlisting>
</para>
</formalpara>
<simpara>Here is an example application.yml for a Sidecar application:</simpara>
<formalpara>
<title>application.yml</title>
<para>
<programlisting language="yaml" linenumbering="unnumbered">server:
port: 5678
spring:
application:
name: sidecar
sidecar:
port: 8000
health-uri: http://localhost:8000/health.json</programlisting>
</para>
</formalpara>
<simpara>The api for the <literal>DiscoveryClient.getInstances()</literal> method is <literal>/hosts/{serviceId}</literal>.
Here is an example response for <literal>/hosts/customers</literal> that returns two instances on
different hosts. This api is accessible to the non-jvm app (if the sidecar is
on port 5678) at <literal><link xl:href="http://localhost:5678/hosts/{serviceId}">http://localhost:5678/hosts/{serviceId}</link></literal>.</simpara>
<formalpara>
<title>/hosts/customers</title>
<para>
<programlisting language="json" linenumbering="unnumbered">[
{
"host": "myhost",
"port": 9000,
"uri": "http://myhost:9000",
"serviceId": "CUSTOMERS",
"secure": false
},
{
"host": "myhost2",
"port": 9000,
"uri": "http://myhost2:9000",
"serviceId": "CUSTOMERS",
"secure": false
}
]</programlisting>
</para>
</formalpara>
<simpara>The Zuul proxy automatically adds routes for each service known in eureka to
<literal>/&lt;serviceId&gt;</literal>, so the customers service is available at <literal>/customers</literal>. The
Non-jvm app can access the customer service via <literal><link xl:href="http://localhost:5678/customers">http://localhost:5678/customers</link></literal>
(assuming the sidecar is listening on port 5678).</simpara>
<simpara>If the Config Server is registered with Eureka, non-jvm application can access
it via the Zuul proxy. If the serviceId of the ConfigServer is <literal>configserver</literal>
and the Sidecar is on port 5678, then it can be accessed at
<link xl:href="http://localhost:5678/configserver">http://localhost:5678/configserver</link></simpara>
<simpara>Non-jvm app can take advantage of the Config Server&#8217;s ability to return YAML
documents. For example, a call to <link xl:href="http://sidecar.local.spring.io:5678/configserver/default-master.yml">http://sidecar.local.spring.io:5678/configserver/default-master.yml</link>
might result in a YAML document like the following</simpara>
<programlisting language="yaml" linenumbering="unnumbered">eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
password: password
info:
description: Spring Cloud Samples
url: https://github.com/spring-cloud-samples</programlisting>
</chapter>
<chapter xml:id="netflix-metrics">
<title>Metrics: Spectator, Servo, and Atlas</title>
<simpara>When used together, Spectator/Servo and Atlas provide a near real-time operational insight platform.</simpara>
<simpara>Spectator and Servo are Netflix&#8217;s metrics collection libraries. Atlas is a Netflix metrics backend to manage dimensional time series data.</simpara>
<simpara>Servo served Netflix for several years and is still usable, but is gradually being phased out in favor of Spectator, which is only designed to work with Java 8. Spring Cloud Netflix provides support for both, but Java 8 based applications are encouraged to use Spectator.</simpara>
<section xml:id="_dimensional_vs_hierarchical_metrics">
<title>Dimensional vs. Hierarchical Metrics</title>
<simpara>Spring Boot Actuator metrics are hierarchical and metrics are separated only by name. These names often follow a naming convention that embeds key/value attribute pairs (dimensions) into the name separated by periods. Consider the following metrics for two endpoints, root and star-star:</simpara>
<programlisting language="json" linenumbering="unnumbered">{
"counter.status.200.root": 20,
"counter.status.400.root": 3,
"counter.status.200.star-star": 5,
}</programlisting>
<simpara>The first metric gives us a normalized count of successful requests against the root endpoint per unit of time. But what if the system had 20 endpoints and you want to get a count of successful requests against all the endpoints? Some hierarchical metrics backends would allow you to specify a wild card such as <literal>counter.status.200.*</literal> that would read all 20 metrics and aggregate the results. Alternatively, you could provide a <literal>HandlerInterceptorAdapter</literal> that intercepts and records a metric like <literal>counter.status.200.all</literal> for all successful requests irrespective of the endpoint, but now you must write 20+1 different metrics. Similarly if you want to know the total number of successful requests for all endpoints in the service, you could specify a wild card such as <literal>counter.status.2*.*</literal>.</simpara>
<simpara>Even in the presence of wildcarding support on a hierarchical metrics backend, naming consistency can be difficult. Specifically the position of these tags in the name string can slip with time, breaking queries. For example, suppose we add an additional dimension to the hierarchical metrics above for HTTP method. Then <literal>counter.status.200.root</literal> becomes <literal>counter.status.200.method.get.root</literal>, etc. Our <literal>counter.status.200.*</literal> suddenly no longer has the same semantic meaning. Furthermore, if the new dimension is not applied uniformly across the codebase, certain queries may become impossible. This can quickly get out of hand.</simpara>
<simpara>Netflix metrics are tagged (a.k.a. dimensional). Each metric has a name, but this single named metric can contain multiple statistics and 'tag' key/value pairs that allows more querying flexibility. In fact, the statistics themselves are recorded in a special tag.</simpara>
<simpara>Recorded with Netflix Servo or Spectator, a timer for the root endpoint described above contains 4 statistics per status code, where the count statistic is identical to Spring Boot Actuator&#8217;s counter. In the event that we have encountered an HTTP 200 and 400 thus far, there will be 8 available data points:</simpara>
<programlisting language="json" linenumbering="unnumbered">{
"root(status=200,stastic=count)": 20,
"root(status=200,stastic=max)": 0.7265630630000001,
"root(status=200,stastic=totalOfSquares)": 0.04759702862580789,
"root(status=200,stastic=totalTime)": 0.2093076914666667,
"root(status=400,stastic=count)": 1,
"root(status=400,stastic=max)": 0,
"root(status=400,stastic=totalOfSquares)": 0,
"root(status=400,stastic=totalTime)": 0,
}</programlisting>
</section>
<section xml:id="_default_metrics_collection">
<title>Default Metrics Collection</title>
<simpara>Without any additional dependencies or configuration, a Spring Cloud based service will autoconfigure a Servo <literal>MonitorRegistry</literal> and begin collecting metrics on every Spring MVC request. By default, a Servo timer with the name <literal>rest</literal> will be recorded for each MVC request which is tagged with:</simpara>
<orderedlist numeration="arabic">
<listitem>
<simpara>HTTP method</simpara>
</listitem>
<listitem>
<simpara>HTTP status (e.g. 200, 400, 500)</simpara>
</listitem>
<listitem>
<simpara>URI (or "root" if the URI is empty), sanitized for Atlas</simpara>
</listitem>
<listitem>
<simpara>The exception class name, if the request handler threw an exception</simpara>
</listitem>
<listitem>
<simpara>The caller, if a request header with a key matching <literal>netflix.metrics.rest.callerHeader</literal> is set on the request. There is no default key for <literal>netflix.metrics.rest.callerHeader</literal>. You must add it to your application properties if you wish to collect caller information.</simpara>
</listitem>
</orderedlist>
<simpara>Set the <literal>netflix.metrics.rest.metricName</literal> property to change the name of the metric from <literal>rest</literal> to a name you provide.</simpara>
<simpara>If Spring AOP is enabled and <literal>org.aspectj:aspectjweaver</literal> is present on your runtime classpath, Spring Cloud will also collect metrics on every client call made with <literal>RestTemplate</literal>. A Servo timer with the name of <literal>restclient</literal> will be recorded for each MVC request which is tagged with:</simpara>
<orderedlist numeration="arabic">
<listitem>
<simpara>HTTP method</simpara>
</listitem>
<listitem>
<simpara>HTTP status (e.g. 200, 400, 500), "CLIENT_ERROR" if the response returned null, or "IO_ERROR" if an <literal>IOException</literal> occurred during the execution of the <literal>RestTemplate</literal> method</simpara>
</listitem>
<listitem>
<simpara>URI, sanitized for Atlas</simpara>
</listitem>
<listitem>
<simpara>Client name</simpara>
</listitem>
</orderedlist>
<warning>
<simpara>Avoid using hardcoded url parameters within <literal>RestTemplate</literal>. When targeting dynamic endpoints use URL variables. This will avoid potential "GC Overhead Limit Reached" issues where <literal>ServoMonitorCache</literal> treats each url as a unique key.</simpara>
</warning>
<programlisting language="java" linenumbering="unnumbered">// recommended
String orderid = "1";
restTemplate.getForObject("http://testeurekabrixtonclient/orders/{orderid}", String.class, orderid)
// avoid
restTemplate.getForObject("http://testeurekabrixtonclient/orders/1", String.class)</programlisting>
</section>
<section xml:id="netflix-metrics-spectator">
<title>Metrics Collection: Spectator</title>
<simpara>To enable Spectator metrics, include a dependency on <literal>spring-boot-starter-spectator</literal>:</simpara>
<programlisting language="xml" linenumbering="unnumbered"> &lt;dependency&gt;
&lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
&lt;artifactId&gt;spring-cloud-starter-netflix-spectator&lt;/artifactId&gt;
&lt;/dependency&gt;</programlisting>
<simpara>In Spectator parlance, a meter is a named, typed, and tagged configuration and a metric represents the value of a given meter at a point in time. Spectator meters are created and controlled by a registry, which currently has several different implementations. Spectator provides 4 meter types: counter, timer, gauge, and distribution summary.</simpara>
<simpara>Spring Cloud Spectator integration configures an injectable <literal>com.netflix.spectator.api.Registry</literal> instance for you. Specifically, it configures a <literal>ServoRegistry</literal> instance in order to unify the collection of REST metrics and the exporting of metrics to the Atlas backend under a single Servo API. Practically, this means that your code may use a mixture of Servo monitors and Spectator meters and both will be scooped up by Spring Boot Actuator <literal>MetricReader</literal> instances and both will be shipped to the Atlas backend.</simpara>
<section xml:id="_spectator_counter">
<title>Spectator Counter</title>
<simpara>A counter is used to measure the rate at which some event is occurring.</simpara>
<programlisting language="java" linenumbering="unnumbered">// create a counter with a name and a set of tags
Counter counter = registry.counter("counterName", "tagKey1", "tagValue1", ...);
counter.increment(); // increment when an event occurs
counter.increment(10); // increment by a discrete amount</programlisting>
<simpara>The counter records a single time-normalized statistic.</simpara>
</section>
<section xml:id="_spectator_timer">
<title>Spectator Timer</title>
<simpara>A timer is used to measure how long some event is taking. Spring Cloud automatically records timers for Spring MVC requests and conditionally <literal>RestTemplate</literal> requests, which can later be used to create dashboards for request related metrics like latency:</simpara>
<figure>
<title>Request Latency</title>
<mediaobject>
<imageobject>
<imagedata fileref="images/RequestLatency.png"/>
</imageobject>
<textobject><phrase>RequestLatency</phrase></textobject>
</mediaobject>
</figure>
<programlisting language="java" linenumbering="unnumbered">// create a timer with a name and a set of tags
Timer timer = registry.timer("timerName", "tagKey1", "tagValue1", ...);
// execute an operation and time it at the same time
T result = timer.record(() -&gt; fooReturnsT());
// alternatively, if you must manually record the time
Long start = System.nanoTime();
T result = fooReturnsT();
timer.record(System.nanoTime() - start, TimeUnit.NANOSECONDS);</programlisting>
<simpara>The timer simultaneously records 4 statistics: count, max, totalOfSquares, and totalTime. The count statistic will always match the single normalized value provided by a counter if you had called <literal>increment()</literal> once on the counter for each time you recorded a timing, so it is rarely necessary to count and time separately for a single operation.</simpara>
<simpara>For <link xl:href="https://github.com/Netflix/spectator/wiki/Timer-Usage#longtasktimer">long running operations</link>, Spectator provides a special <literal>LongTaskTimer</literal>.</simpara>
</section>
<section xml:id="_spectator_gauge">
<title>Spectator Gauge</title>
<simpara>Gauges are used to determine some current value like the size of a queue or number of threads in a running state. Since gauges are sampled, they provide no information about how these values fluctuate between samples.</simpara>
<simpara>The normal use of a gauge involves registering the gauge once in initialization with an id, a reference to the object to be sampled, and a function to get or compute a numeric value based on the object. The reference to the object is passed in separately and the Spectator registry will keep a weak reference to the object. If the object is garbage collected, then Spectator will automatically drop the registration. See <link xl:href="https://github.com/Netflix/spectator/wiki/Gauge-Usage#using-lambda">the note</link> in Spectator&#8217;s documentation about potential memory leaks if this API is misused.</simpara>
<programlisting language="java" linenumbering="unnumbered">// the registry will automatically sample this gauge periodically
registry.gauge("gaugeName", pool, Pool::numberOfRunningThreads);
// manually sample a value in code at periodic intervals -- last resort!
registry.gauge("gaugeName", Arrays.asList("tagKey1", "tagValue1", ...), 1000);</programlisting>
</section>
<section xml:id="_spectator_distribution_summaries">
<title>Spectator Distribution Summaries</title>
<simpara>A distribution summary is used to track the distribution of events. It is similar to a timer, but more general in that the size does not have to be a period of time. For example, a distribution summary could be used to measure the payload sizes of requests hitting a server.</simpara>
<programlisting language="java" linenumbering="unnumbered">// the registry will automatically sample this gauge periodically
DistributionSummary ds = registry.distributionSummary("dsName", "tagKey1", "tagValue1", ...);
ds.record(request.sizeInBytes());</programlisting>
</section>
</section>
<section xml:id="netflix-metrics-servo">
<title>Metrics Collection: Servo</title>
<warning>
<simpara>If your code is compiled on Java 8, please use Spectator instead of Servo as Spectator is destined to replace Servo entirely in the long term.</simpara>
</warning>
<simpara>In Servo parlance, a monitor is a named, typed, and tagged configuration and a metric represents the value of a given monitor at a point in time. Servo monitors are logically equivalent to Spectator meters. Servo monitors are created and controlled by a <literal>MonitorRegistry</literal>. In spite of the above warning, Servo does have a <link xl:href="https://github.com/Netflix/servo/wiki/Getting-Started">wider array</link> of monitor options than Spectator has meters.</simpara>
<simpara>Spring Cloud integration configures an injectable <literal>com.netflix.servo.MonitorRegistry</literal> instance for you. Once you have created the appropriate <literal>Monitor</literal> type in Servo, the process of recording data is wholly similar to Spectator.</simpara>
<section xml:id="_creating_servo_monitors">
<title>Creating Servo Monitors</title>
<simpara>If you are using the Servo <literal>MonitorRegistry</literal> instance provided by Spring Cloud (specifically, an instance of <literal>DefaultMonitorRegistry</literal>), Servo provides convenience classes for retrieving <link xl:href="https://github.com/Netflix/spectator/wiki/Servo-Comparison#dynamiccounter">counters</link> and <link xl:href="https://github.com/Netflix/spectator/wiki/Servo-Comparison#dynamictimer">timers</link>. These convenience classes ensure that only one <literal>Monitor</literal> is registered for each unique combination of name and tags.</simpara>
<simpara>To manually create a Monitor type in Servo, especially for the more exotic monitor types for which convenience methods are not provided, instantiate the appropriate type by providing a <literal>MonitorConfig</literal> instance:</simpara>
<programlisting language="java" linenumbering="unnumbered">MonitorConfig config = MonitorConfig.builder("timerName").withTag("tagKey1", "tagValue1").build();
// somewhere we should cache this Monitor by MonitorConfig
Timer timer = new BasicTimer(config);
monitorRegistry.register(timer);</programlisting>
</section>
</section>
<section xml:id="netflix-metrics-atlas">
<title>Metrics Backend: Atlas</title>
<simpara>Atlas was developed by Netflix to manage dimensional time series data for near real-time operational insight. Atlas features in-memory data storage, allowing it to gather and report very large numbers of metrics, very quickly.</simpara>
<simpara>Atlas captures operational intelligence. Whereas business intelligence is data gathered for analyzing trends over time, operational intelligence provides a picture of what is currently happening within a system.</simpara>
<simpara>Spring Cloud provides a <literal>spring-cloud-starter-netflix-atlas</literal> that has all the dependencies you need. Then just annotate your Spring Boot application with <literal>@EnableAtlas</literal> and provide a location for your running Atlas server with the <literal>netflix.atlas.uri</literal> property.</simpara>
<section xml:id="_global_tags">
<title>Global tags</title>
<simpara>Spring Cloud enables you to add tags to every metric sent to the Atlas backend. Global tags can be used to separate metrics by application name, environment, region, etc.</simpara>
<simpara>Each bean implementing <literal>AtlasTagProvider</literal> will contribute to the global tag list:</simpara>
<programlisting language="java" linenumbering="unnumbered">@Bean
AtlasTagProvider atlasCommonTags(
@Value("${spring.application.name}") String appName) {
return () -&gt; Collections.singletonMap("app", appName);
}</programlisting>
</section>
<section xml:id="_using_atlas">
<title>Using Atlas</title>
<simpara>To bootstrap a in-memory standalone Atlas instance:</simpara>
<programlisting language="bash" linenumbering="unnumbered">$ curl -LO https://github.com/Netflix/atlas/releases/download/v1.4.2/atlas-1.4.2-standalone.jar
$ java -jar atlas-1.4.2-standalone.jar</programlisting>
<tip>
<simpara>An Atlas standalone node running on an r3.2xlarge (61GB RAM) can handle roughly 2 million metrics per minute for a given 6 hour window.</simpara>
</tip>
<simpara>Once running and you have collected a handful of metrics, verify that your setup is correct by listing tags on the Atlas server:</simpara>
<programlisting language="bash" linenumbering="unnumbered">$ curl http://ATLAS/api/v1/tags</programlisting>
<tip>
<simpara>After executing several requests against your service, you can gather some very basic information on the request latency of every request by pasting the following url in your browser: <literal><link xl:href="http://ATLAS/api/v1/graph?q=name,rest,:eq,:avg">http://ATLAS/api/v1/graph?q=name,rest,:eq,:avg</link></literal></simpara>
</tip>
<simpara>The Atlas wiki contains a <link xl:href="https://github.com/Netflix/atlas/wiki/Single-Line">compilation of sample queries</link> for various scenarios.</simpara>
<simpara>Make sure to check out the <link xl:href="https://github.com/Netflix/atlas/wiki/Alerting-Philosophy">alerting philosophy</link> and docs on using <link xl:href="https://github.com/Netflix/atlas/wiki/DES">double exponential smoothing</link> to generate dynamic alert thresholds.</simpara>
</section>
</section>
<section xml:id="retrying-failed-requests">
<title>Retrying Failed Requests</title>
<simpara>Spring Cloud Netflix offers a variety of ways to make HTTP requests. You can use a load balanced
<literal>RestTemplate</literal>, Ribbon, or Feign. No matter how you choose to your HTTP requests, there is always
a chance the request may fail. When a request fails you may want to have the request retried
automatically. To accomplish this when using Sping Cloud Netflix you need to include
<link xl:href="https://github.com/spring-projects/spring-retry">Spring Retry</link> on your application&#8217;s classpath.
When Spring Retry is present load balanced <literal>RestTemplates</literal>, Feign, and Zuul will automatically
retry any failed requests (assuming you configuration allows it to).</simpara>
<section xml:id="_backoff_policies">
<title>BackOff Policies</title>
<simpara>By default no backoff policy is used when retrying requests. If you would like to configure
a backoff policy you will need to create a bean of type <literal>LoadBalancedBackOffPolicyFactory</literal>
which will be used to create a <literal>BackOffPolicy</literal> for a given service.</simpara>
<programlisting language="java" linenumbering="unnumbered">@Configuration
public class MyConfiguration {
@Bean
LoadBalancedBackOffPolicyFactory backOffPolciyFactory() {
return new LoadBalancedBackOffPolicyFactory() {
@Override
public BackOffPolicy createBackOffPolicy(String service) {
return new ExponentialBackOffPolicy();
}
};
}
}</programlisting>
</section>
<section xml:id="_configuration">
<title>Configuration</title>
<simpara>Anytime Ribbon is used with Spring Retry you can control the retry functionality by configuring
certain Ribbon properties. The properties you can use are
<literal>client.ribbon.MaxAutoRetries</literal>, <literal>client.ribbon.MaxAutoRetriesNextServer</literal>, and
<literal>client.ribbon.OkToRetryOnAllOperations</literal>. See the <link xl:href="https://github.com/Netflix/ribbon/wiki/Getting-Started#the-properties-file-sample-clientproperties">Ribbon documentation</link>
for a description of what there properties do.</simpara>
<warning>
<simpara>Enabling <literal>client.ribbon.OkToRetryOnAllOperations</literal> includes retring POST requests wich can have a impact
on the server&#8217;s resources due to the buffering of the request&#8217;s body.</simpara>
</warning>
<simpara>In addition you may want to retry requests when certain status codes are returned in the
response. You can list the response codes you would like the Ribbon client to retry using the
property <literal>clientName.ribbon.retryableStatusCodes</literal>. For example</simpara>
<programlisting language="yaml" linenumbering="unnumbered">clientName:
ribbon:
retryableStatusCodes: 404,502</programlisting>
<simpara>You can also create a bean of type <literal>LoadBalancedRetryPolicy</literal> and implement the <literal>retryableStatusCode</literal>
method to determine whether you want to retry a request given the status code.</simpara>
</section>
<section xml:id="_zuul">
<title>Zuul</title>
<simpara>You can turn off Zuul&#8217;s retry functionality by setting <literal>zuul.retryable</literal> to <literal>false</literal>. You
can also disable retry functionality on route by route basis by setting
<literal>zuul.routes.routename.retryable</literal> to <literal>false</literal>.</simpara>
</section>
</section>
</chapter>
<chapter xml:id="_http_clients">
<title>HTTP Clients</title>
<simpara>Spring Cloud Netflix will automatically create the HTTP client used by Ribbon, Feign, and
Zuul for you. However you can also provide your own HTTP clients customized how you please
yourself. To do this you can either create a bean of type <literal>ClosableHttpClient</literal> if you
are using the Apache Http Cient, or <literal>OkHttpClient</literal> if you are using OK HTTP.</simpara>
<note>
<simpara>When you create your own HTTP client you are also responsible for implementing
the correct connection management strategies for these clients. Doing this improperly
can result in resource management issues.</simpara>
</note>
</chapter>
</book>