Files
spring-cloud-static/spring-cloud-netflix/2.0.1.RELEASE/spring-cloud-netflix.xml
2018-07-31 18:56:50 +00:00

2022 lines
122 KiB
XML
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?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>2018-07-31</date>
</info>
<preface>
<title></title>
<simpara><emphasis role="strong">2.0.1.RELEASE</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 difficult to do and can be 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 the Eureka Client in your project, use the starter with a group ID of <literal>org.springframework.cloud</literal> and an artifact ID of <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&#8201;&#8212;&#8201;such as host, port, health indicator URL, home page, and other details.
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>The following example shows a minimal Eureka client application:</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>Note that the preceding example shows a normal <link xl:href="https://projects.spring.io/spring-boot/">Spring Boot</link> application.
By having <literal>spring-cloud-starter-netflix-eureka-client</literal> on the classpath, your application automatically registers with the Eureka Server. Configuration is required to locate the Eureka server, as shown in the following example:</simpara>
<formalpara>
<title>application.yml</title>
<para>
<screen>eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/</screen>
</para>
</formalpara>
<simpara>In the preceding example, "defaultZone" is a magic string fallback value that provides the service URL for any client that does not express a preference (in other words, it is a useful default).</simpara>
<simpara>The default application name (that is, the 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 &#8220;instance&#8221; (that is, it registers itself) and a &#8220;client&#8221; (it can query the registry to locate other services).
The instance behaviour is driven by <literal>eureka.instance.*</literal> configuration keys, but the defaults are fine if you ensure that your application has a value for <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 on 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 is automatically added to your eureka client if one of the <literal>eureka.client.serviceUrl.defaultZone</literal> URLs has credentials embedded in it (curl style, as follows: <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 is applied to the calls from the client to the server.</simpara>
<note>
<simpara>Because of a limitation in Eureka, it is not possible to support per-server basic auth credentials, so only the first set that are found is 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 <literal>/info</literal> and <literal>/health</literal> 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 (such as <literal>server.servletPath=/custom</literal>). The following example shows the default values for the two settings:</simpara>
<formalpara>
<title>application.yml</title>
<para>
<screen>eureka:
instance:
statusPageUrlPath: ${server.servletPath}/info
healthCheckUrlPath: ${server.servletPath}/health</screen>
</para>
</formalpara>
<simpara>These links show up in the metadata that is consumed by clients and are used in some scenarios to decide whether to send requests to your application, so it is helpful if they are accurate.</simpara>
<note>
<simpara>In Dalston it was also required to set the status and health check URLs when changing
that management context path. This requirement was removed beginning in Edgware.</simpara>
</note>
</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>:</simpara>
<itemizedlist>
<listitem>
<simpara><literal>eureka.instance.[nonSecurePortEnabled]=[false]</literal></simpara>
</listitem>
<listitem>
<simpara><literal>eureka.instance.[securePortEnabled]=[true]</literal></simpara>
</listitem>
</itemizedlist>
<simpara>Doing so makes Eureka publish instance information that shows an explicit preference for secure communication.
The Spring Cloud <literal>DiscoveryClient</literal> always returns a URI starting with <literal>https</literal> for a service configured this way.
Similarly, when a service is configured this way, the Eureka (native) instance information has a secure health check URL.</simpara>
<simpara>Because of the way Eureka works internally, it still publishes a non-secure URL for the status and home pages unless you also override those explicitly.
You can use placeholders to configure the eureka instance URLs, as shown in the following example:</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&#8201;&#8212;&#8201;for example, by using <literal>${eureka.instance.hostName}</literal>.)</simpara>
<note>
<simpara>If your application runs behind a proxy, and the SSL termination is in the proxy (for example, if you run in Cloud Foundry or other platforms as a service), then you need to ensure that the proxy &#8220;forwarded&#8221; headers are intercepted and handled by the application.
If the Tomcat container embedded in a Spring Boot application has explicit configuration for the 'X-Forwarded-\*` headers, this happens automatically.
The links rendered by your app to itself being wrong (the wrong host, port, or protocol) is a sign that you got this configuration wrong.</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 does not propagate the current health check status of the application, per the Spring Boot Actuator.
Consequently, after successful registration, Eureka always announces that the application is in 'UP' state. This behavior can be altered by enabling Eureka health checks, which results in propagating application status to Eureka.
As a consequence, every other application does not send traffic to applications in states other then 'UP'.
The following example shows how to enable health checks for the client:</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> causes undesirable side effects, such as registering in Eureka with an <literal>UNKNOWN</literal> status.</simpara>
</warning>
<simpara>If you require more control over the health checks, 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 is 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 information such as hostname, IP address, port numbers, the 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 metadata is accessible in the remote clients.
In general, additional metadata does not change the behavior of the client, unless the client is made aware of the meaning of the metadata.
There are a couple of special cases, described later in this document, where Spring Cloud already assigns meaning to the metadata map.</simpara>
<section xml:id="_using_eureka_on_cloud_foundry">
<title>Using Eureka on Cloud Foundry</title>
<simpara>Cloud Foundry has a global router so that all instances of the same app have the same hostname (other PaaS solutions with a similar architecture have the same arrangement).
This is not necessarily a barrier to using Eureka.
However, 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 that you can distinguish between the instances on the client (for example, in a custom load balancer).
By default, the <literal>eureka.instance.instanceId</literal> is <literal>vcap.application.instance_id</literal>, as shown in the following 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 Cloud Foundry 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, the Eureka instance must be configured to be AWS-aware. You can do so 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> as follows:</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 (that is, there is only one service per host).
Spring Cloud Eureka provides a sensible default, which is defined as follows:</simpara>
<simpara><literal>${spring.cloud.client.hostname}:${spring.application.name}:${spring.application.instance_id:${server.port}}}</literal></simpara>
<simpara>An example is <literal>myhost:myappname:8080</literal>.</simpara>
<simpara>By using Spring Cloud, you can override this value by providing a unique identifier in <literal>eureka.instance.instanceId</literal>, as shown in the following 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 the metadata shown in the preceding example and multiple service instances deployed on localhost, the random value is inserted there to make the instance unique.
In Cloud Foundry, the <literal>vcap.application.instance_id</literal> is populated automatically in a Spring Boot application, so the random value is not needed.</simpara>
</section>
</section>
<section xml:id="_using_the_eurekaclient">
<title>Using the EurekaClient</title>
<simpara>Once you have an application 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 so is to use the native <literal>com.netflix.discovery.EurekaClient</literal> (as opposed to the Spring Cloud <literal>DiscoveryClient</literal>), as shown in the following example:</simpara>
<screen>@Autowired
private EurekaClient discoveryClient;
public String serviceUrl() {
InstanceInfo instance = discoveryClient.getNextServerFromEureka("STORES", false);
return instance.getHomePageUrl();
}</screen>
<tip>
<simpara>Do not use the <literal>EurekaClient</literal> in a <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 a 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 auto-configures a transport client based on Spring <literal>RestTemplate</literal>.
The following example shows Jersey being excluded:</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 need not use the raw Netflix <literal>EurekaClient</literal>.
Also, it is usually 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 <link linkend="spring-cloud-ribbon">Spring <literal>RestTemplate</literal></link> through the logical Eureka service identifiers (VIPs) instead of physical URLs.
To configure Ribbon with a fixed list of physical servers, you can 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 (not specific to Netflix) for discovery clients, as shown in the following example:</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
(through the client&#8217;s <literal>serviceUrl</literal>) with a default duration of 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 by setting <literal>eureka.instance.leaseRenewalIntervalInSeconds</literal>.
Setting it to a value of less than 30 speeds up the process of getting clients connected to other services.
In production, it is probably better to stick with the default, because of internal computations 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, you may prefer that those clients use services within the same zone before trying services in another zone.
To set that up, 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 so by 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 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>
<simpara>This section describes how to set up a Eureka server.</simpara>
<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 a group ID of <literal>org.springframework.cloud</literal> and an artifact ID of <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>The following example shows a minimal 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 for the normal Eureka functionality under <literal>/eureka/*</literal>.</simpara>
<simpara>The following links have some Eureka background reading: <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, depending on <literal>spring-cloud-starter-netflix-eureka-server</literal> can cause failures on application startup.
To remedy this issue, add the Spring Boot Gradle plugin and import the Spring cloud starter parent bom as follows:</simpara>
<formalpara>
<title>build.gradle</title>
<para>
<programlisting language="java" linenumbering="unnumbered">buildscript {
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:{spring-boot-docs-version}")
}
}
apply plugin: "spring-boot"
dependencyManagement {
imports {
mavenBom "org.springframework.cloud:spring-cloud-dependencies:{spring-cloud-version}"
}
}</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 back end 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 do not have to go to the registry for every 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 do not provide it, the service runs and works, but it fills 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="spring-cloud-eureka-server-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 (such as Cloud Foundry) keeping it alive.
In standalone mode, you might prefer to switch off the client side behavior so that it does not keep trying and failing to reach its peers.
The following example shows how to switch off the client-side behavior:</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="spring-cloud-eureka-server-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 behavior, so all you need to do to make it work is add a valid <literal>serviceUrl</literal> to a peer, as shown in the following example:</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 the preceding example, we have a YAML file that can be used to run the same server on two hosts (<literal>peer1</literal> and <literal>peer2</literal>) by running it in different Spring profiles.
You could use this configuration to test the peer awareness on a single host (there is 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 (by default, it is looked up by using <literal>java.net.InetAddress</literal>).</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 synchronize
the registrations amongst themselves.
If the peers are physically separated (inside a data center or between multiple data centers), then the system can, in principle, survive &#8220;split-brain&#8221; type failures.</simpara>
</section>
<section xml:id="spring-cloud-eureka-server-prefer-ip-address">
<title>When to Prefer IP Address</title>
<simpara>In some cases, it is preferable for Eureka to advertise the IP addresses of services rather than the hostname.
Set <literal>eureka.instance.preferIpAddress</literal> to <literal>true</literal> and, when the application registers with eureka, it uses its IP address rather than its hostname.</simpara>
<tip>
<simpara>If the hostname cannot be determined by Java, then the IP address is sent to Eureka.
Only explict way of setting the hostname is by setting <literal>eureka.instance.hostname</literal> property.
You can set your hostname at the run-time by using an environment variable&#8201;&#8212;&#8201;for example, <literal>eureka.instance.hostname=${HOST_NAME}</literal>.</simpara>
</tip>
</section>
<section xml:id="_securing_the_eureka_server">
<title>Securing The Eureka Server</title>
<simpara>You can secure your Eureka server simply by adding Spring Security to your
server&#8217;s classpath via <literal>spring-boot-starter-security</literal>. By default when Spring Security is on the classpath it will require that
a valid CSRF token be sent with every request to the app. Eureka clients will not generally possess a valid
cross site request forgery (CSRF) token you will need to disable this requirement for the <literal>/eureka/**</literal> endpoints.
For example:</simpara>
<programlisting language="java" linenumbering="unnumbered">@EnableWebSecurity
class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().ignoringAntMatchers("/eureka/**");
super.configure(http);
}
}</programlisting>
<simpara>For more information on CSRF see the <link xl:href="https://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#csrf">Spring Security documentation</link>.</simpara>
<simpara>A demo Eureka Server can be found in the Spring Cloud Samples <link xl:href="https://github.com/spring-cloud-samples/eureka/tree/Eureka-With-Security">repo</link>.</simpara>
</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, as shown in the following example:</simpara>
<figure>
<title>Microservice Graph</title>
<mediaobject>
<imageobject>
<imagedata fileref="https://raw.githubusercontent.com/spring-cloud/spring-cloud-netflix/master/docs/src/main/asciidoc/images/Hystrix.png"/>
</imageobject>
<textobject><phrase>Hystrix</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 exceed <literal>circuitBreaker.requestVolumeThreshold</literal> (default: 20 requests) and the failure 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="https://raw.githubusercontent.com/spring-cloud/spring-cloud-netflix/master/docs/src/main/asciidoc/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 recover.
The fallback can be another Hystrix protected call, static data, or a sensible empty value.
Fallbacks may be chained so that the first fallback makes some other business call, which in turn falls back to static data.</simpara>
<section xml:id="_how_to_include_hystrix">
<title>How to Include Hystrix</title>
<simpara>To include Hystrix in your project, use the starter with a group ID of <literal>org.springframework.cloud</literal>
and a artifact ID of <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>The following example shows a minimal Eureka server with a Hystrix circuit breaker:</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">&#8220;javanica&#8221;</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="netflix-hystrix-starter">
<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 does 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 through configuration or directly in the annotation, by asking it to use a different &#8220;Isolation Strategy&#8221;.
The following example demonstrates setting the thread in the annotation:</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>.
If you encounter a runtime exception that says it cannot find the scoped context, you need to use the same thread.</simpara>
<simpara>You also have the option to set the <literal>hystrix.shareSecurityContext</literal> property to <literal>true</literal>.
Doing so auto-configures a Hystrix concurrency strategy plugin hook to transfer the <literal>SecurityContext</literal> from your main thread to the one used by the Hystrix command.
Hystrix does not let multiple Hystrix concurrency strategy be registered so an extension mechanism is available by declaring your own <literal>HystrixConcurrencyStrategy</literal> as a Spring bean.
Spring Cloud looks 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, as shown in the following example:</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> and set
<literal>management.endpoints.web.exposure.include: hystrix.stream</literal>.
Doing so exposes the <literal>/actuator/hystrix.stream</literal> as a management endpoint, as shown in the following example:</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="https://raw.githubusercontent.com/spring-cloud/spring-cloud-netflix/master/docs/src/main/asciidoc/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 the Hystrix Dashboard</title>
<simpara>To include the Hystrix Dashboard in your project, use the starter with a group ID of <literal>org.springframework.cloud</literal> and an artifact ID of <literal>spring-cloud-starter-netflix-hystrix-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>.
Then visit <literal>/hystrix</literal> and point the dashboard to an individual instance&#8217;s <literal>/hystrix.stream</literal> endpoint in a Hystrix client application.</simpara>
<note>
<simpara>When connecting to a <literal>/hystrix.stream</literal> endpoint that 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 instance&#8217;s 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 through Eureka.
Running Turbine requires annotating your main class with the <literal>@EnableTurbine</literal> annotation (for example, by 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 and then appending <literal>/hystrix.stream</literal> to it.
If the instance&#8217;s metadata contains <literal>management.port</literal>, it is used instead of the <literal>port</literal> value for the <literal>/hystrix.stream</literal> endpoint.
By default, the metadata entry called <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 <literal>turbine.appConfig</literal> configuration key is a list of Eureka serviceIds that turbine uses to lookup instances.
The turbine stream is then used in the Hystrix dashboard with a URL similar to the following:</simpara>
<simpara><literal><link xl:href="http://my.turbine.server:8080/turbine.stream?cluster=CLUSTERNAME">http://my.turbine.server:8080/turbine.stream?cluster=CLUSTERNAME</link></literal></simpara>
<simpara>The cluster parameter can be omitted if the name is <literal>default</literal>.
The <literal>cluster</literal> parameter must match an entry in <literal>turbine.aggregator.clusterConfig</literal>.
Values returned from Eureka are upper-case. Consequently, the following example works if there is an application called <literal>customers</literal> registered with Eureka:</simpara>
<screen>turbine:
aggregator:
clusterConfig: CUSTOMERS
appConfig: customers</screen>
<simpara>If you need to customize which cluster names should be used by Turbine (because you do not 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 as an instance of <literal>InstanceInfo</literal>.
The default value is <literal>appName</literal>, which means that the Eureka <literal>serviceId</literal> becomes the cluster key (that is, the <literal>InstanceInfo</literal> for customers has an <literal>appName</literal> of <literal>CUSTOMERS</literal>).
A different example is <literal>turbine.clusterNameExpression=aSGName</literal>, which gets the cluster name from the AWS ASG name.
The following listing shows another example:</simpara>
<screen>turbine:
aggregator:
clusterConfig: SYSTEM,USER
appConfig: customers,stores,ui,admin
clusterNameExpression: metadata['cluster']</screen>
<simpara>In the preceding example, the cluster name from four services is pulled from their metadata map and is expected to have values that include <literal>SYSTEM</literal> and <literal>USER</literal>.</simpara>
<simpara>To use the &#8220;default&#8221; 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. To ad Turnbine, create a Spring Boot application and annotate it with <literal>@EnableTurbine</literal>.</simpara>
<note>
<simpara>By default, Spring Cloud lets Turbine use the host and port to allow multiple processes per host, per cluster.
If you want the native Netflix behavior built into Turbine to <emphasis>not</emphasis> allow multiple processes per host, per cluster (the key to the instance ID is the hostname), set <literal>turbine.combineHostPort=false</literal>.</simpara>
</note>
<section xml:id="_clusters_endpoint">
<title>Clusters Endpoint</title>
<simpara>In some situations it might be useful for other applications to know what custers have been configured
in Turbine. To support this you can use the <literal>/clusters</literal> endpoint which will return a JSON array of
all the configured clusters.</simpara>
<formalpara>
<title>GET /clusters</title>
<para>
<programlisting language="json" linenumbering="unnumbered">[
{
"name": "RACES",
"link": "http://localhost:8383/turbine.stream?cluster=RACES"
},
{
"name": "WEB",
"link": "http://localhost:8383/turbine.stream?cluster=WEB"
}
]</programlisting>
</para>
</formalpara>
<simpara>This endpoint can be disabled by setting <literal>turbine.endpoints.clusters.enabled</literal> to <literal>false</literal>.</simpara>
</section>
</section>
<section xml:id="_turbine_stream">
<title>Turbine Stream</title>
<simpara>In some environments (such as in a PaaS setting), the classic Turbine model of pulling metrics from all the distributed Hystrix commands does not work.
In that case, you might want to have your Hystrix commands push metrics to Turbine. Spring Cloud enables that with messaging.
To do so on the client, add a dependency to <literal>spring-cloud-netflix-hystrix-stream</literal> and the <literal>spring-cloud-starter-stream-*</literal> of your choice.
See the <link xl:href="https://docs.spring.io/spring-cloud-stream/docs/current/reference/htmlsingle/">Spring Cloud Stream documentation</link> for details on the brokers and how to configure the client credentials. It should work out of the box for a local broker.</simpara>
<simpara>On the server side, create a Spring Boot application and annotate it with <literal>@EnableTurbineStream</literal>.
The Turbine Stream server requires the use of Spring Webflux, therefore <literal>spring-boot-starter-webflux</literal> needs to be included in your project.
By default <literal>spring-boot-starter-webflux</literal> is included when adding <literal>spring-cloud-starter-netflix-turbine-stream</literal> to your application.</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 are prefixed by their respective <literal>serviceId</literal>, followed by a dot (<literal>.</literal>), and 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.
You can then add the Stream binder of your choice&#8201;&#8212;&#8201;such as <literal>spring-cloud-starter-stream-rabbit</literal>.</simpara>
<simpara>Turbine Stream server also supports the <literal>cluster</literal> parameter.
Unlike Turbine server, Turbine Stream uses eureka serviceIds as cluster names and these are not configurable.</simpara>
<simpara>If Turbine Stream server is running on port 8989 on <literal>my.turbine.server</literal> and you have two eureka serviceIds <literal>customers</literal> and <literal>products</literal> in your environment, the following URLs will be available on your Turbine Stream server. <literal>default</literal> and empty cluster name will provide all metrics that Turbine Stream server receives.</simpara>
<screen>http://my.turbine.sever:8989/turbine.stream?cluster=customers
http://my.turbine.sever:8989/turbine.stream?cluster=products
http://my.turbine.sever:8989/turbine.stream?cluster=default
http://my.turbine.sever:8989/turbine.stream</screen>
<simpara>So, you can use eureka serviceIds as cluster names for your Turbine dashboard (or any compatible dashboard).
You dont need to configure any properties like <literal>turbine.appConfig</literal>, <literal>turbine.clusterNameExpression</literal> and <literal>turbine.aggregator.clusterConfig</literal> for your Turbine Stream server.</simpara>
<note>
<simpara>Turbine Stream server gathers all metrics from the configured input channel with Spring Cloud Stream. It means that it doesnt gather Hystrix metrics actively from each instance. It just can provide metrics that were already gathered into the input channel by each instance.</simpara>
</note>
</section>
</chapter>
<chapter xml:id="spring-cloud-ribbon">
<title>Client Side Load Balancer: Ribbon</title>
<simpara>Ribbon is a client-side load balancer that gives you a lot of control over the behavior of HTTP and TCP clients.
Feign already uses Ribbon, so, if you use <literal>@FeignClient</literal>, 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 (for example, by using the <literal>@FeignClient</literal> annotation).
On demand, Spring Cloud creates a new ensemble as an <literal>ApplicationContext</literal> for each named client by 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 a group ID of <literal>org.springframework.cloud</literal> and an artifact ID of <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 by using external properties in <literal>&lt;client&gt;.ribbon.*</literal>, which is similar to 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>, as shown in the following example:</simpara>
<programlisting language="java" linenumbering="unnumbered">@Configuration
@RibbonClient(name = "custom", configuration = CustomConfiguration.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>CustomConfiguration</literal> (where the latter generally overrides the former).</simpara>
<warning>
<simpara>The <literal>CustomConfiguration</literal> clas must be a <literal>@Configuration</literal> class, but take care that it is not in a <literal>@ComponentScan</literal> for the main application context.
Otherwise, it is 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, you can put it in a separate, non-overlapping package or specify the packages to scan explicitly in the <literal>@ComponentScan</literal>).</simpara>
</warning>
<simpara>The following table shows the beans that Spring Cloud Netflix provides by default for Ribbon:</simpara>
<informaltable frame="topbot" rowsep="1" colsep="1">
<?dbhtml table-width="60%"?>
<?dbfo table-width="60%"?>
<?dblatex table-width="60%"?>
<tgroup cols="3">
<colspec colname="col_1" colwidth="85*"/>
<colspec colname="col_2" colwidth="85*"/>
<colspec colname="col_3" colwidth="85*"/>
<thead>
<row>
<entry align="center" valign="top">Bean Type</entry>
<entry align="center" valign="top">Bean Name</entry>
<entry align="center" valign="top">Class Name</entry>
</row>
</thead>
<tbody>
<row>
<entry align="left" valign="top"><simpara><literal>IClientConfig</literal></simpara></entry>
<entry align="left" valign="top"><simpara><literal>ribbonClientConfig</literal></simpara></entry>
<entry align="left" valign="top"><simpara><literal>DefaultClientConfigImpl</literal></simpara></entry>
</row>
<row>
<entry align="left" valign="top"><simpara><literal>IRule</literal></simpara></entry>
<entry align="left" valign="top"><simpara><literal>ribbonRule</literal></simpara></entry>
<entry align="left" valign="top"><simpara><literal>ZoneAvoidanceRule</literal></simpara></entry>
</row>
<row>
<entry align="left" valign="top"><simpara><literal>IPing</literal></simpara></entry>
<entry align="left" valign="top"><simpara><literal>ribbonPing</literal></simpara></entry>
<entry align="left" valign="top"><simpara><literal>DummyPing</literal></simpara></entry>
</row>
<row>
<entry align="left" valign="top"><simpara><literal>ServerList&lt;Server&gt;</literal></simpara></entry>
<entry align="left" valign="top"><simpara><literal>ribbonServerList</literal></simpara></entry>
<entry align="left" valign="top"><simpara><literal>ConfigurationBasedServerList</literal></simpara></entry>
</row>
<row>
<entry align="left" valign="top"><simpara><literal>ServerListFilter&lt;Server&gt;</literal></simpara></entry>
<entry align="left" valign="top"><simpara><literal>ribbonServerListFilter</literal></simpara></entry>
<entry align="left" valign="top"><simpara><literal>ZonePreferenceServerListFilter</literal></simpara></entry>
</row>
<row>
<entry align="left" valign="top"><simpara><literal>ILoadBalancer</literal></simpara></entry>
<entry align="left" valign="top"><simpara><literal>ribbonLoadBalancer</literal></simpara></entry>
<entry align="left" valign="top"><simpara><literal>ZoneAwareLoadBalancer</literal></simpara></entry>
</row>
<row>
<entry align="left" valign="top"><simpara><literal>ServerListUpdater</literal></simpara></entry>
<entry align="left" valign="top"><simpara><literal>ribbonServerListUpdater</literal></simpara></entry>
<entry align="left" valign="top"><simpara><literal>PollingServerListUpdater</literal></simpara></entry>
</row>
</tbody>
</tgroup>
</informaltable>
<simpara>Creating a bean of one of those type and placing it in a <literal>@RibbonClient</literal> configuration (such as <literal>FooConfiguration</literal> above) lets you override each one of the beans described, as shown in the following 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>The include statement in the preceding example replaces <literal>NoOpPing</literal> with <literal>PingUrl</literal> and provides a custom <literal>serverListFilter</literal>.</simpara>
</section>
<section xml:id="_customizing_the_default_for_all_ribbon_clients">
<title>Customizing the Default for All Ribbon Clients</title>
<simpara>A default configuration can be provided for all Ribbon Clients by 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_by_setting_properties">
<title>Customizing the Ribbon Client by Setting Properties</title>
<simpara>Starting with version 1.2.0, Spring Cloud Netflix now supports customizing Ribbon clients by setting 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 lets you change behavior at start up time in different environments.</simpara>
<simpara>The following list shows the supported properties&gt;:</simpara>
<itemizedlist>
<listitem>
<simpara><literal>&lt;clientName&gt;.ribbon.NFLoadBalancerClassName</literal>: Should implement <literal>ILoadBalancer</literal></simpara>
</listitem>
<listitem>
<simpara><literal>&lt;clientName&gt;.ribbon.NFLoadBalancerRuleClassName</literal>: Should implement <literal>IRule</literal></simpara>
</listitem>
<listitem>
<simpara><literal>&lt;clientName&gt;.ribbon.NFLoadBalancerPingClassName</literal>: Should implement <literal>IPing</literal></simpara>
</listitem>
<listitem>
<simpara><literal>&lt;clientName&gt;.ribbon.NIWSServerListClassName</literal>: Should implement <literal>ServerList</literal></simpara>
</listitem>
<listitem>
<simpara><literal>&lt;clientName&gt;.ribbon.NIWSServerListFilterClassName</literal>: Should implement <literal>ServerListFilter</literal></simpara>
</listitem>
</itemizedlist>
<note>
<simpara>Classes defined in these properties have precedence over beans defined by 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 called <literal>users</literal>, you could set the following properties:</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 (that is, 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>. Its purpose is to make metadata available to the load balancer without using AWS AMI metadata (which is what Netflix relies on).
By default, the server list is constructed with &#8220;zone&#8221; information, as provided in the instance metadata (so, on the remote clients, set <literal>eureka.instance.metadataMap.zone</literal>).
If that is missing and if the <literal>approximateZoneFromHostname</literal> flag is set, it can use the domain name from the server hostname as a proxy for the zone.
Once the zone information is available, it can be used in a <literal>ServerListFilter</literal>.
By default, it is used to locate a server in the same zone as the client, because the default is a <literal>ZonePreferenceServerListFilter</literal>.
By default, the zone of the client is determined in the same way as the remote instances (that is, through <literal>eureka.instance.metadataMap.zone</literal>).</simpara>
<note>
<simpara>The orthodox &#8220;archaius&#8221; way to set the client zone is through a configuration property called "@zone".
If it is available, Spring Cloud uses that in preference to all other settings (note that the key must 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 (that is, the <literal>eureka.client.region</literal>, which defaults to "us-east-1", for compatibility 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 that you do not have to hard code their URLs in clients.
However, if you prefer not to use Eureka, Ribbon and Feign also work.
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.
You can supply the configuration as follows:</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 <literal>ribbon.eureka.enabled</literal> property to <literal>false</literal> explicitly disables the use of Eureka in Ribbon, as shown in the following example:</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, as shown in the following 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 on the first request to the named client.
This lazy loading behavior can be changed to instead eagerly load these child application contexts at startup, by specifying the names of the Ribbon clients, as shown in the following example:</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 <literal>THREAD</literal>, the thread isolation strategy for Hystrix is used for all routes.
In that case, the <literal>HystrixThreadPoolKey</literal> is set to <literal>RibbonCommand</literal> as the default.
It means that HystrixCommands for all routes are executed in the same Hystrix thread pool.
This behavior can be changed with the following configuration:</simpara>
<formalpara>
<title>application.yml</title>
<para>
<screen>zuul:
threadPool:
useSeparateThreadPools: true</screen>
</para>
</formalpara>
<simpara>The preceding example results in HystrixCommands being executed in the Hystrix thread pool for each route.</simpara>
<simpara>In this case, the default <literal>HystrixThreadPoolKey</literal> is the same as the service ID for each route.
To add a prefix to <literal>HystrixThreadPoolKey</literal>, set <literal>zuul.threadPool.threadPoolKeyPrefix</literal> to the value that you want to add, as shown in the following 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 &#8220;canary&#8221; test, 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 is used by your <literal>IRule</literal> implementation to choose a target server, as shown in the following example:</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 of <literal>FilterConstants.LOAD_BALANCER_KEY</literal>, it is passed to the <literal>choose</literal> method of the <literal>IRule</literal> implementation.
The code shown in the preceding example must be executed before <literal>RibbonRoutingFilter</literal> is executed.
Zuul&#8217;s pre filter is the best place to do that.
You can access HTTP headers and query parameters through the <literal>RequestContext</literal> in pre filter, so it can be used to determine the <literal>LOAD_BALANCER_KEY</literal> that is passed to Ribbon.
If you do not put any value with <literal>LOAD_BALANCER_KEY</literal> in <literal>RequestContext</literal>, null is passed as a parameter of the <literal>choose</literal> method.</simpara>
</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 by letting a source push changes to the client.
Archaius uses Dynamic&lt;Type&gt;Property classes as handles to properties, as shown in the following example:</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 that Archaius can read properties from the Spring Environment.
This bridge allows Spring Boot projects to use the normal configuration toolchain while letting them configure the Netflix tools as documented (for the most part).</simpara>
</chapter>
<chapter xml:id="_router_and_filter_zuul">
<title>Router and Filter: Zuul</title>
<simpara>Routing is 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 from 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 lets rules and filters 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>The default Hystrix isolation pattern (<literal>ExecutionIsolationStrategy</literal>) for all routes is <literal>SEMAPHORE</literal>.
<literal>zuul.ribbonIsolationStrategy</literal> can be changed to <literal>THREAD</literal> if that 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 a group ID of <literal>org.springframework.cloud</literal> and a artifact ID of <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 common use case where a UI application wants to make proxy calls to one or more back end services.
This feature is useful for a user interface to proxy to the back end services it requires, avoiding the need to manage CORS and authentication concerns independently for all the back ends.</simpara>
<simpara>To enable it, annotate a Spring Boot main class with <literal>@EnableZuulProxy</literal>. Doing so causes local calls to be forwarded to the appropriate service.
By convention, a service with an ID of <literal>users</literal> receives requests from the proxy located at <literal>/users</literal> (with the prefix stripped).
The proxy uses Ribbon to locate an instance to which to forward through discovery.
All requests are executed in a <link linkend="hystrix-fallbacks-for-routes">hystrix command</link>, so failures appear in Hystrix metrics.
Once the circuit is open, the proxy does 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 (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 is also included in the explicitly configured routes map, it is unignored, as shown in the following example:</simpara>
<formalpara>
<title>application.yml</title>
<para>
<programlisting language="yaml" linenumbering="unnumbered"> zuul:
ignoredServices: '*'
routes:
users: /myusers/**</programlisting>
</para>
</formalpara>
<simpara>In the preceding example, all services are ignored, <emphasis role="strong">except</emphasis> for <literal>users</literal>.</simpara>
<simpara>To augment or change the proxy routes, you can add external configuration, as follows:</simpara>
<formalpara>
<title>application.yml</title>
<para>
<programlisting language="yaml" linenumbering="unnumbered"> zuul:
routes:
users: /myusers/**</programlisting>
</para>
</formalpara>
<simpara>The preceding example means that HTTP calls to <literal>/myusers</literal> get forwarded to the <literal>users</literal> service (for example <literal>/myusers/101</literal> is forwarded to <literal>/101</literal>).</simpara>
<simpara>To get more fine-grained control over a route, you can specify the path and the serviceId independently, as follows:</simpara>
<formalpara>
<title>application.yml</title>
<para>
<programlisting language="yaml" linenumbering="unnumbered"> zuul:
routes:
users:
path: /myusers/**
serviceId: users_service</programlisting>
</para>
</formalpara>
<simpara>The preceding example means that HTTP calls to <literal>/myusers</literal> get forwarded to the <literal>users_service</literal> service.
The route must have a <literal>path</literal> that can be specified as an ant-style pattern, so <literal>/myusers/*</literal> only matches one level, but <literal>/myusers/**</literal> matches hierarchically.</simpara>
<simpara>The location of the back end can be specified as either a <literal>serviceId</literal> (for a service from discovery) or a <literal>url</literal> (for a physical location), as shown in the following example:</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 do not get executed as a <literal>HystrixCommand</literal>, nor do they load-balance multiple URLs with Ribbon.
To achieve those goals, you can specify a <literal>serviceId</literal> with a static list of servers, as follows:</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 configuring a Ribbon client for the <literal>serviceId</literal> (doing so requires disabling Eureka support in Ribbon&#8201;&#8212;&#8201;see <link linkend="spring-cloud-ribbon-without-eureka">above for more information</link>), as shown in the following example:</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 a convention between <literal>serviceId</literal> and routes by using <literal>regexmapper</literal>.
It uses regular-expression named groups to extract variables from <literal>serviceId</literal> and inject them into a route pattern, as shown in the following example:</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>The preceding example means that a <literal>serviceId</literal> of <literal>myusers-v1</literal> is mapped to route <literal>/v1/myusers/**</literal>.
Any regular expression is accepted, but all named groups must be present in both <literal>servicePattern</literal> and <literal>routePattern</literal>.
If <literal>servicePattern</literal> does not match a <literal>serviceId</literal>, the default behavior is used.
In the preceding example, a <literal>serviceId</literal> of <literal>myusers</literal> is mapped to the "/myusers/**" route (with 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>.
By default, the proxy prefix is stripped from the request before the request is forwarded by (you can switch this behavior off with <literal>zuul.stripPrefix=false</literal>).
You can also switch off the stripping of the service-specific prefix from individual routes, as shown in the following example:</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 the preceding example, requests to <literal>/myusers/101</literal> are forwarded to <literal>/myusers/101</literal> on the <literal>users</literal> 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 can see that it also has a <literal>retryable</literal> flag.
Set that flag to <literal>true</literal> to have the Ribbon client automatically retry failed requests.
You can also set that flag to <literal>true</literal> when you need to modify the parameters of the retry operations that use the Ribbon client configuration.</simpara>
<simpara>By default, the <literal>X-Forwarded-Host</literal> header is added to the forwarded requests.
To turn it off, set <literal>zuul.addProxyHeaders = false</literal>.
By default, the prefix path is stripped, and the request to the back end picks up a <literal>X-Forwarded-Prefix</literal> header (<literal>/myusers</literal> in the examples shown earlier).</simpara>
<simpara>If you set a default route (<literal>/</literal>), an application with <literal>@EnableZuulProxy</literal> could act as a standalone server. For example, <literal>zuul.route.home: /</literal> would route all traffic ("/**") 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.
The following example shows how to create ignored patterns:</simpara>
<formalpara>
<title>application.yml</title>
<para>
<programlisting language="yaml" linenumbering="unnumbered"> zuul:
ignoredPatterns: /**/admin/**
routes:
users: /myusers/**</programlisting>
</para>
</formalpara>
<simpara>The preceding example means that all calls (such as <literal>/myusers/101</literal>) are forwarded to <literal>/101</literal> on the <literal>users</literal> service.
However, calls including <literal>/admin/</literal> do 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 is lost when using a properties file.
The following example shows such a YAML file:</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 might 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 <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>You can share headers between services in the same system, but you probably do not 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 together (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), you might be able to let them flow from the back end 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 useful to the caller, so it is recommended that you make (at least) <literal>Set-Cookie</literal> and <literal>Cookie</literal> into sensitive headers for routes that are not part of your domain.
Even for routes that are part of your domain, try to think carefully about what it means before letting cookies flow between them and the proxy.</simpara>
<simpara>The sensitive headers can be configured as a comma-separated list per route, as shown in the following example:</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 need not set it unless you want it to be different.
This is new in Spring Cloud Netflix 1.1 (in 1.0, the user had no control over headers, and all cookies flowed in both directions).</simpara>
</note>
<simpara>The <literal>sensitiveHeaders</literal> are a blacklist, and the default is not empty.
Consequently, to make Zuul send all headers (except the <literal>ignored</literal> ones), you must explicitly set it to the empty list.
Doing so is necessary if you want to pass cookie or authorization headers to your back end. The following example shows how to use <literal>sensitiveHeaders</literal>:</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>You can also set sensitive headers, by setting <literal>zuul.sensitiveHeaders</literal>.
If <literal>sensitiveHeaders</literal> is set on a route, it overrides the global <literal>sensitiveHeaders</literal> setting.</simpara>
</section>
<section xml:id="_ignored_headers">
<title>Ignored Headers</title>
<simpara>In addition to the route-sensitive headers, you can set a global value called <literal>zuul.ignoredHeaders</literal> for values (both request and response) that should be discarded during interactions with downstream services.
By default, if Spring Security is not on the classpath, these are empty.
Otherwise, they are initialized to a set of well known &#8220;security&#8221; headers (for example, involving caching) as specified by Spring Security.
The assumption in this case is that the downstream services might add these headers, too, but we want the values from the proxy.
To not discard these well known security headers when Spring Security is on the classpath, you can set <literal>zuul.ignoreSecurityHeaders</literal> to <literal>false</literal>.
Doing so 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>By default, if you use <literal>@EnableZuulProxy</literal> with the Spring Boot Actuator, you enable 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> returns 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>.
Doing so produces 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 <literal>POST</literal> to <literal>/routes</literal> forces a refresh of the existing routes (for example, when 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 <literal>POST</literal> to <literal>/routes</literal> is a way to force the change
to happen immediately.</simpara>
</note>
</section>
<section xml:id="_filters_endpoint">
<title>Filters Endpoint</title>
<simpara>A <literal>GET</literal> to the filters endpoint at <literal>/filters</literal> returns a map of Zuul filters by type.
For each filter type in the map, you get 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 &#8220;strangle&#8221; 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 the clients of the old endpoints but redirect some of the requests to new ones.</simpara>
<simpara>The following example shows the configuration details for a &#8220;strangle&#8221; scenario:</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 the preceding example, we are strangle the &#8220;legacy&#8221; application, 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.
Paths in <literal>/second/**</literal> are forwarded so that they can be handled locally (for example, with a normal Spring <literal>@RequestMapping</literal>).
Paths in <literal>/third/**</literal> are also forwarded but with a different prefix (<literal>/third/foo</literal> is forwarded to <literal>/3rd/foo</literal>).</simpara>
<note>
<simpara>The ignored patterns aren&#8217;t completely ignored, they just are not 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 use <literal>@EnableZuulProxy</literal>, you can use the proxy paths to upload files and it should work, so long as the files are small.
For large files there is an alternative path that bypasses the Spring <literal>DispatcherServlet</literal> (to avoid multipart processing) in "/zuul/*".
In other words, if you have <literal>zuul.routes.customers=/customers/**</literal>, then you can <literal>POST</literal> large files to <literal>/zuul/customers/*</literal>.
The servlet path is externalized via <literal>zuul.servletPath</literal>.
If the proxy route takes you through a Ribbon load balancer, extremely large files also require elevated timeout settings, as shown in the following example:</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), as shown in the following example:</simpara>
<programlisting language="bash" linenumbering="unnumbered">$ curl -v -H "Transfer-Encoding: chunked" \
-F "file=@mylarge.iso" localhost:9999/zuul/simple/file</programlisting>
</section>
<section xml:id="_query_string_encoding">
<title>Query String Encoding</title>
<simpara>When processing the incoming request, query params are decoded so that they can be available for possible modifications in Zuul filters.
They are then re-encoded the back end request is rebuilt in the route filters.
The result can be different than the original input if (for example) it was encoded with Javascript&#8217;s <literal>encodeURIComponent()</literal> method.
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, as shown in the following example:</simpara>
<formalpara>
<title>application.yml</title>
<para>
<programlisting language="yaml" linenumbering="unnumbered"> zuul:
forceOriginalQueryStringEncoding: true</programlisting>
</para>
</formalpara>
<note>
<simpara>This special flag works only with <literal>SimpleHostRoutingFilter</literal>. Also, you loose the ability to easily override
query parameters with <literal>RequestContext.getCurrentContext().setRequestQueryParams(someOverriddenParameters)</literal>, because
the query string is now fetched directly on the original <literal>HttpServletRequest</literal>.</simpara>
</note>
</section>
<section xml:id="_plain_embedded_zuul">
<title>Plain Embedded Zuul</title>
<simpara>If you use <literal>@EnableZuulServer</literal> (instead of <literal>@EnableZuulProxy</literal>), you can also run a Zuul server without proxying or selectively switch on parts of the proxying platform.
Any beans that you add to the application of type <literal>ZuulFilter</literal> are installed automatically (as they are with <literal>@EnableZuulProxy</literal>) but without any of the proxy filters being added automatically.</simpara>
<simpara>In that case, the routes into the Zuul server are still specified by configuring "zuul.routes.*", but there is no service discovery and no proxying. Consequently, the "serviceId" and "url" settings are ignored.
The following example maps all paths in "/api/**" to the Zuul filter chain:</simpara>
<formalpara>
<title>application.yml</title>
<para>
<programlisting language="yaml" linenumbering="unnumbered"> zuul:
routes:
api: /api/**</programlisting>
</para>
</formalpara>
</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-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters">the Zuul filters package</link> for the list of filters that you can enable.
If you want to disable one, 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>FallbackProvider</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.
The following example shows a relatively simple <literal>FallbackProvider</literal> implementation:</simpara>
<programlisting language="java" linenumbering="unnumbered">class MyFallbackProvider implements FallbackProvider {
@Override
public String getRoute() {
return "customers";
}
@Override
public ClientHttpResponse fallbackResponse(String route, final Throwable cause) {
if (cause instanceof HystrixTimeoutException) {
return response(HttpStatus.GATEWAY_TIMEOUT);
} else {
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>
<simpara>The following example shows how the route configuration for the previous example might appear:</simpara>
<programlisting language="yaml" linenumbering="unnumbered">zuul:
routes:
customers: /customers/**</programlisting>
<simpara>If you would like to provide a default fallback for all routes, you can create a bean of type <literal>FallbackProvider</literal> and have the <literal>getRoute</literal> method return <literal>*</literal> or <literal>null</literal>, as shown in the following example:</simpara>
<programlisting language="java" linenumbering="unnumbered">class MyFallbackProvider implements FallbackProvider {
@Override
public String getRoute() {
return "*";
}
@Override
public ClientHttpResponse fallbackResponse(String route, Throwable throwable) {
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>
</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, you have two options, based on your configuration:</simpara>
<itemizedlist>
<listitem>
<simpara>If Zuul uses service discovery, you need to configure these timeouts with the
<literal>ribbon.ReadTimeout</literal> and <literal>ribbon.SocketTimeout</literal> Ribbon properties.</simpara>
</listitem>
</itemizedlist>
<simpara>If you have configured Zuul routes by specifying URLs, you 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 the <literal>Location</literal> header</title>
<simpara>If Zuul is fronting a web application, you may need to re-write the <literal>Location</literal> header when the web application redirects through a HTTP status code of <literal>3XX</literal>.
Otherwise, the browser redirects to the web application&#8217;s URL instead of the Zuul URL.
You can configure a <literal>LocationRewriteFilter</literal> Zuul filter to re-write the <literal>Location</literal> header to the Zuul&#8217;s URL.
It also adds back the stripped global and route-specific prefixes.
The following example adds a filter by using 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>
<caution>
<simpara>Use this filter carefully. The filter acts on the <literal>Location</literal> header of ALL <literal>3XX</literal> response codes, which may not be appropriate in all scenarios, such as when redirecting the user to an external URL.</simpara>
</caution>
</section>
<section xml:id="_metrics">
<title>Metrics</title>
<simpara>Zuul will provide metrics under the Actuator metrics endpoint for any failures that might occur when routing requests.
These metrics can be viewed by hitting <literal>/actuator/metrics</literal>. The metrics will have a name that has the format
<literal>ZUUL::EXCEPTION:errorCause:statusCode</literal>.</simpara>
</section>
<section xml:id="zuul-developer-guide">
<title>Zuul Developer Guide</title>
<simpara>For a general overview of how Zuul works, 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 lets Spring MVC be in control of the routing.
In this case, Zuul buffers requests.
If there is a need to go through Zuul without buffering requests (for example, for large file uploads), the Servlet is also installed outside of the Spring Dispatcher.
By default, the servlet has an address of <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 used by the filters installed by Spring Cloud Netflix (more on these <link linkend="zuul-developer-guide-enable-filters">later</link>).</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, depending 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 the filters installed by <literal>@EnableZuulServer</literal>. The additional filters in the &#8220;proxy&#8221; enable routing functionality. If you want a &#8220;blank&#8221; Zuul, you should use <literal>@EnableZuulServer</literal>.</simpara>
</section>
<section xml:id="zuul-developer-guide-enable-filters">
<title><literal>@EnableZuulServer</literal> Filters</title>
<simpara><literal>@EnableZuulServer</literal> 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>
<itemizedlist>
<listitem>
<simpara>Pre filters:</simpara>
<itemizedlist>
<listitem>
<simpara><literal>ServletDetectionFilter</literal>: Detects whether the request is through the Spring Dispatcher. Sets a boolean with a key of <literal>FilterConstants.IS_DISPATCHER_SERVLET_REQUEST_KEY</literal>.</simpara>
</listitem>
<listitem>
<simpara><literal>FormBodyWrapperFilter</literal>: Parses form data and re-encodes it for downstream requests.</simpara>
</listitem>
<listitem>
<simpara><literal>DebugFilter</literal>: If the <literal>debug</literal> request parameter is set, sets <literal>RequestContext.setDebugRouting()</literal> and <literal>RequestContext.setDebugRequest()</literal> to <literal>true</literal>.
*Route filters:</simpara>
</listitem>
<listitem>
<simpara><literal>SendForwardFilter</literal>: Forwards requests by 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>
</listitem>
<listitem>
<simpara>Post filters:</simpara>
<itemizedlist>
<listitem>
<simpara><literal>SendResponseFilter</literal>: Writes responses from proxied requests to the current response.</simpara>
</listitem>
</itemizedlist>
</listitem>
<listitem>
<simpara>Error filters:</simpara>
<itemizedlist>
<listitem>
<simpara><literal>SendErrorFilter</literal>: Forwards to <literal>/error</literal> (by default) if <literal>RequestContext.getThrowable()</literal> is not null. You can change the default forwarding path (<literal>/error</literal>) by setting the <literal>error.path</literal> property.</simpara>
</listitem>
</itemizedlist>
</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> (such as 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 are refreshed.</simpara>
<simpara>In addition to the filters described earlier, the following filters are installed (as normal Spring Beans):</simpara>
<itemizedlist>
<listitem>
<simpara>Pre filters:</simpara>
<itemizedlist>
<listitem>
<simpara><literal>PreDecorationFilter</literal>: Determines where and how to route, depending on the supplied <literal>RouteLocator</literal>. It also sets various proxy-related headers for downstream requests.</simpara>
</listitem>
</itemizedlist>
</listitem>
<listitem>
<simpara>Route filters:</simpara>
<itemizedlist>
<listitem>
<simpara><literal>RibbonRoutingFilter</literal>: 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:</simpara>
<itemizedlist>
<listitem>
<simpara>Apache <literal>HttpClient</literal>: The default client.</simpara>
</listitem>
<listitem>
<simpara>Squareup <literal>OkHttpClient</literal> v3: 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: Enabled by setting <literal>ribbon.restclient.enabled=true</literal>. This client has limitations, including that it does not support the PATCH method, but it also has built-in retry.</simpara>
</listitem>
</itemizedlist>
</listitem>
<listitem>
<simpara><literal>SimpleHostRoutingFilter</literal>: Sends requests to predetermined URLs through an Apache HttpClient. URLs are found in <literal>RequestContext.getRouteHost()</literal>.</simpara>
</listitem>
</itemizedlist>
</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>
<simpara>This section includes the following examples:</simpara>
<itemizedlist>
<listitem>
<simpara><xref linkend="zuul-developer-guide-sample-pre-filter"/></simpara>
</listitem>
<listitem>
<simpara><xref linkend="zuul-developer-guide-sample-route-filter"/></simpara>
</listitem>
<listitem>
<simpara><xref linkend="zuul-developer-guide-sample-post-filter"/></simpara>
</listitem>
</itemizedlist>
<section xml:id="zuul-developer-guide-sample-pre-filter">
<title>How to Write a Pre Filter</title>
<simpara>Pre filters 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.
The following example shows a Zuul pre filter:</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("sample") != null) {
// put the serviceId in `RequestContext`
ctx.put(SERVICE_ID_KEY, request.getParameter("foo"));
}
return null;
}
}</programlisting>
<simpara>The preceding filter populates <literal>SERVICE_ID_KEY</literal> from the <literal>sample</literal> request parameter.
In practice, you should not do that kind of direct mapping. Instead, the service ID should be looked up from the value of <literal>sample</literal> instead.</simpara>
<simpara>Now that <literal>SERVICE_ID_KEY</literal> is populated, <literal>PreDecorationFilter</literal> does not run and <literal>RibbonRoutingFilter</literal> runs.</simpara>
<tip>
<simpara>If you want to route to a full URL, call <literal>ctx.setRouteHost(url)</literal> instead.</simpara>
</tip>
<simpara>To modify the path to which routing filters forward, set the <literal>REQUEST_URI_KEY</literal>.</simpara>
</section>
<section xml:id="zuul-developer-guide-sample-route-filter">
<title>How to Write a Route Filter</title>
<simpara>Route filters run after pre filters and make requests to other services.
Much of the work here is to translate request and response data to and from the model required by the client.
The following example shows a Zuul route filter:</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 preceding filter translates Servlet request information into OkHttp3 request information, executes an HTTP request, and translates OkHttp3 response information to the Servlet response.</simpara>
</section>
<section xml:id="zuul-developer-guide-sample-post-filter">
<title>How to Write a Post Filter</title>
<simpara>Post filters typically manipulate the response. The following filter adds a random <literal>UUID</literal> as the <literal>X-Sample</literal> header:</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-Sample", UUID.randomUUID().toString());
return null;
}
}</programlisting>
<note>
<simpara>Other manipulations, such as transforming the response body, are much more complex and computationally intensive.</simpara>
</note>
</section>
</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 URLs.
By default, Ribbon clients are lazily loaded by Spring Cloud on first call.
This behavior can be changed for Zuul by using the following configuration, which results eager loading of the child Ribbon related Application contexts at application startup time.
The following example shows how to enable eager loading:</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 with which 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 an HTTP API to get all of the instances (by host and port) for a given service.
You can also proxy service calls through an embedded Zuul proxy that gets its route entries from Eureka.
The Spring Cloud Config Server can be accessed directly through host lookup or through the Zuul Proxy.
The non-JVM application should implement a health check so the Sidecar can report to Eureka whether the app is up or down.</simpara>
<simpara>To include Sidecar in your project, use the dependency with a group ID of <literal>org.springframework.cloud</literal>
and artifact ID or <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 on which the non-JVM application listens.
This is so the Sidecar can properly register the application with Eureka.
The <literal>sidecar.health-uri</literal> is a URI accessible on the non-JVM application that mimics a Spring Boot health indicator.
It should return a JSON document that resembles the following:</simpara>
<formalpara>
<title>health-uri-document</title>
<para>
<programlisting language="json" linenumbering="unnumbered">{
"status":"UP"
}</programlisting>
</para>
</formalpara>
<simpara>HThe following application.yml example shows sample configuration 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>.
The following example response for <literal>/hosts/customers</literal> returns two instances on different hosts:</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>This API is accessible to the non-JVM application (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>
<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 application can access the customer service at <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, the non-JVM application can access it through the Zuul proxy.
If the <literal>serviceId</literal> 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 applications 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 resembling 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="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 create your HTTP requests, there is always a chance that a request may fail.
When a request fails, you may want to have the request be retried automatically.
To do so 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 automatically retry any failed requests (assuming your configuration allows doing so).</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 need to create a bean of type <literal>LoadBalancedBackOffPolicyFactory</literal>, which is used to create a <literal>BackOffPolicy</literal> for a given service, as shown in the following example:</simpara>
<programlisting language="java" linenumbering="unnumbered">@Configuration
public class MyConfiguration {
@Bean
LoadBalancedBackOffPolicyFactory backOffPolicyFactory() {
return new LoadBalancedBackOffPolicyFactory() {
@Override
public BackOffPolicy createBackOffPolicy(String service) {
return new ExponentialBackOffPolicy();
}
};
}
}</programlisting>
</section>
<section xml:id="_configuration">
<title>Configuration</title>
<simpara>When you use Ribbon with Spring Retry, you can control the retry functionality by configuring certain Ribbon properties.
To do so, set the <literal>client.ribbon.MaxAutoRetries</literal>, <literal>client.ribbon.MaxAutoRetriesNextServer</literal>, and <literal>client.ribbon.OkToRetryOnAllOperations</literal> properties.
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 these properties do.</simpara>
<warning>
<simpara>Enabling <literal>client.ribbon.OkToRetryOnAllOperations</literal> includes retrying POST requests, which can have an impact
on the server&#8217;s resources, due to the buffering of the request 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 by setting the <literal>clientName.ribbon.retryableStatusCodes</literal> property, as shown in the following 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 retry a request given the status code.</simpara>
<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 a 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 automatically creates the HTTP client used by Ribbon, Feign, and Zuul for you.
However, you can also provide your own HTTP clients customized as you need them to be.
To do so, you can 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 so improperly can result in resource management issues.</simpara>
</note>
</chapter>
</book>