3486 lines
166 KiB
HTML
3486 lines
166 KiB
HTML
<!DOCTYPE html>
|
||
<html lang="en">
|
||
<head>
|
||
<meta charset="UTF-8">
|
||
<!--[if IE]><meta http-equiv="X-UA-Compatible" content="IE=edge"><![endif]-->
|
||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||
<meta name="generator" content="Asciidoctor 1.5.8">
|
||
<title>Spring Cloud Netflix</title>
|
||
<link rel="stylesheet" href="css/spring.css">
|
||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
|
||
|
||
<style>
|
||
.hidden {
|
||
display: none;
|
||
}
|
||
|
||
.switch {
|
||
border-width: 1px 1px 0 1px;
|
||
border-style: solid;
|
||
border-color: #7a2518;
|
||
display: inline-block;
|
||
}
|
||
|
||
.switch--item {
|
||
padding: 10px;
|
||
background-color: #ffffff;
|
||
color: #7a2518;
|
||
display: inline-block;
|
||
cursor: pointer;
|
||
}
|
||
|
||
.switch--item:not(:first-child) {
|
||
border-width: 0 0 0 1px;
|
||
border-style: solid;
|
||
border-color: #7a2518;
|
||
}
|
||
|
||
.switch--item.selected {
|
||
background-color: #7a2519;
|
||
color: #ffffff;
|
||
}
|
||
</style>
|
||
<script src="https://cdnjs.cloudflare.com/ajax/libs/zepto/1.2.0/zepto.min.js"></script>
|
||
<script type="text/javascript">
|
||
function addBlockSwitches() {
|
||
$('.primary').each(function() {
|
||
primary = $(this);
|
||
createSwitchItem(primary, createBlockSwitch(primary)).item.addClass("selected");
|
||
primary.children('.title').remove();
|
||
});
|
||
$('.secondary').each(function(idx, node) {
|
||
secondary = $(node);
|
||
primary = findPrimary(secondary);
|
||
switchItem = createSwitchItem(secondary, primary.children('.switch'));
|
||
switchItem.content.addClass('hidden');
|
||
findPrimary(secondary).append(switchItem.content);
|
||
secondary.remove();
|
||
});
|
||
}
|
||
|
||
function createBlockSwitch(primary) {
|
||
blockSwitch = $('<div class="switch"></div>');
|
||
primary.prepend(blockSwitch);
|
||
return blockSwitch;
|
||
}
|
||
|
||
function findPrimary(secondary) {
|
||
candidate = secondary.prev();
|
||
while (!candidate.is('.primary')) {
|
||
candidate = candidate.prev();
|
||
}
|
||
return candidate;
|
||
}
|
||
|
||
function createSwitchItem(block, blockSwitch) {
|
||
blockName = block.children('.title').text();
|
||
content = block.children('.content').first().append(block.next('.colist'));
|
||
item = $('<div class="switch--item">' + blockName + '</div>');
|
||
item.on('click', '', content, function(e) {
|
||
$(this).addClass('selected');
|
||
$(this).siblings().removeClass('selected');
|
||
e.data.siblings('.content').addClass('hidden');
|
||
e.data.removeClass('hidden');
|
||
});
|
||
blockSwitch.append(item);
|
||
return {'item': item, 'content': content};
|
||
}
|
||
|
||
$(addBlockSwitches);
|
||
</script>
|
||
|
||
</head>
|
||
<body class="book toc2 toc-left">
|
||
<div id="header">
|
||
<h1>Spring Cloud Netflix</h1>
|
||
<div id="toc" class="toc2">
|
||
<div id="toctitle">Table of Contents</div>
|
||
<ul class="sectlevel1">
|
||
<li><a href="#service-discovery-eureka-clients">1. Service Discovery: Eureka Clients</a>
|
||
<ul class="sectlevel2">
|
||
<li><a href="#netflix-eureka-client-starter">1.1. How to Include Eureka Client</a></li>
|
||
<li><a href="#registering-with-eureka">1.2. Registering with Eureka</a></li>
|
||
<li><a href="#authenticating-with-the-eureka-server">1.3. Authenticating with the Eureka Server</a></li>
|
||
<li><a href="#status-page-and-health-indicator">1.4. Status Page and Health Indicator</a></li>
|
||
<li><a href="#registering-a-secure-application">1.5. Registering a Secure Application</a></li>
|
||
<li><a href="#eurekas-health-checks">1.6. Eureka’s Health Checks</a></li>
|
||
<li><a href="#eureka-metadata-for-instances-and-clients">1.7. Eureka Metadata for Instances and Clients</a>
|
||
<ul class="sectlevel3">
|
||
<li><a href="#using-eureka-on-cloud-foundry">1.7.1. Using Eureka on Cloud Foundry</a></li>
|
||
<li><a href="#using-eureka-on-aws">1.7.2. Using Eureka on AWS</a></li>
|
||
<li><a href="#changing-the-eureka-instance-id">1.7.3. Changing the Eureka Instance ID</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#using-the-eurekaclient">1.8. Using the EurekaClient</a>
|
||
<ul class="sectlevel3">
|
||
<li><a href="#eurekaclient-without-jersey">1.8.1. EurekaClient without Jersey</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#alternatives-to-the-native-netflix-eurekaclient">1.9. Alternatives to the Native Netflix EurekaClient</a></li>
|
||
<li><a href="#why-is-it-so-slow-to-register-a-service">1.10. Why Is It so Slow to Register a Service?</a></li>
|
||
<li><a href="#zones">1.11. Zones</a></li>
|
||
<li><a href="#refreshing-eureka-clients">1.12. Refreshing Eureka Clients</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#spring-cloud-eureka-server">2. Service Discovery: Eureka Server</a>
|
||
<ul class="sectlevel2">
|
||
<li><a href="#netflix-eureka-server-starter">2.1. How to Include Eureka Server</a></li>
|
||
<li><a href="#spring-cloud-running-eureka-server">2.2. How to Run a Eureka Server</a></li>
|
||
<li><a href="#spring-cloud-eureka-server-zones-and-regions">2.3. High Availability, Zones and Regions</a></li>
|
||
<li><a href="#spring-cloud-eureka-server-standalone-mode">2.4. Standalone Mode</a></li>
|
||
<li><a href="#spring-cloud-eureka-server-peer-awareness">2.5. Peer Awareness</a></li>
|
||
<li><a href="#spring-cloud-eureka-server-prefer-ip-address">2.6. When to Prefer IP Address</a></li>
|
||
<li><a href="#securing-the-eureka-server">2.7. Securing The Eureka Server</a></li>
|
||
<li><a href="#disabling-ribbon-with-eureka-server-and-client-starters">2.8. Disabling Ribbon with Eureka Server and Client starters</a></li>
|
||
<li><a href="#jdk-11-support">2.9. JDK 11 Support</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#circuit-breaker-spring-cloud-circuit-breaker-with-hystrix">3. Circuit Breaker: Spring Cloud Circuit Breaker With Hystrix</a>
|
||
<ul class="sectlevel2">
|
||
<li><a href="#disabling-spring-cloud-circuit-breaker-hystrix">3.1. Disabling Spring Cloud Circuit Breaker Hystrix</a></li>
|
||
<li><a href="#configuring-hystrix-circuit-breakers">3.2. Configuring Hystrix Circuit Breakers</a>
|
||
<ul class="sectlevel3">
|
||
<li><a href="#default-configuration">3.2.1. Default Configuration</a>
|
||
<ul class="sectlevel4">
|
||
<li><a href="#reactive-example">Reactive Example</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#specific-circuit-breaker-configuration">3.2.2. Specific Circuit Breaker Configuration</a>
|
||
<ul class="sectlevel4">
|
||
<li><a href="#reactive-example-2">Reactive Example</a></li>
|
||
</ul>
|
||
</li>
|
||
</ul>
|
||
</li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#circuit-breaker-hystrix-clients">4. Circuit Breaker: Hystrix Clients</a>
|
||
<ul class="sectlevel2">
|
||
<li><a href="#how-to-include-hystrix">4.1. How to Include Hystrix</a></li>
|
||
<li><a href="#netflix-hystrix-starter">4.2. Propagating the Security Context or Using Spring Scopes</a></li>
|
||
<li><a href="#health-indicator">4.3. Health Indicator</a></li>
|
||
<li><a href="#hystrix-metrics-stream">4.4. Hystrix Metrics Stream</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#circuit-breaker-hystrix-dashboard">5. Circuit Breaker: Hystrix Dashboard</a></li>
|
||
<li><a href="#hystrix-timeouts-and-ribbon-clients">6. Hystrix Timeouts And Ribbon Clients</a>
|
||
<ul class="sectlevel2">
|
||
<li><a href="#netflix-hystrix-dashboard-starter">6.1. How to Include the Hystrix Dashboard</a></li>
|
||
<li><a href="#turbine">6.2. Turbine</a>
|
||
<ul class="sectlevel3">
|
||
<li><a href="#clusters-endpoint">6.2.1. Clusters Endpoint</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#turbine-stream">6.3. Turbine Stream</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#spring-cloud-ribbon">7. Client Side Load Balancer: Ribbon</a>
|
||
<ul class="sectlevel2">
|
||
<li><a href="#netflix-ribbon-starter">7.1. How to Include Ribbon</a></li>
|
||
<li><a href="#customizing-the-ribbon-client">7.2. Customizing the Ribbon Client</a></li>
|
||
<li><a href="#customizing-the-default-for-all-ribbon-clients">7.3. Customizing the Default for All Ribbon Clients</a></li>
|
||
<li><a href="#customizing-the-ribbon-client-by-setting-properties">7.4. Customizing the Ribbon Client by Setting Properties</a></li>
|
||
<li><a href="#using-ribbon-with-eureka">7.5. Using Ribbon with Eureka</a></li>
|
||
<li><a href="#spring-cloud-ribbon-without-eureka">7.6. Example: How to Use Ribbon Without Eureka</a></li>
|
||
<li><a href="#example-disable-eureka-use-in-ribbon">7.7. Example: Disable Eureka Use in Ribbon</a></li>
|
||
<li><a href="#using-the-ribbon-api-directly">7.8. Using the Ribbon API Directly</a></li>
|
||
<li><a href="#ribbon-child-context-eager-load">7.9. Caching of Ribbon Configuration</a></li>
|
||
<li><a href="#how-to-configure-hystrix-thread-pools">7.10. How to Configure Hystrix Thread Pools</a></li>
|
||
<li><a href="#how-to-provdie-a-key-to-ribbon">7.11. How to Provide a Key to Ribbon’s <code>IRule</code></a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#external-configuration-archaius">8. External Configuration: Archaius</a></li>
|
||
<li><a href="#router-and-filter-zuul">9. Router and Filter: Zuul</a>
|
||
<ul class="sectlevel2">
|
||
<li><a href="#netflix-zuul-starter">9.1. How to Include Zuul</a></li>
|
||
<li><a href="#netflix-zuul-reverse-proxy">9.2. Embedded Zuul Reverse Proxy</a></li>
|
||
<li><a href="#zuul-http-client">9.3. Zuul Http Client</a></li>
|
||
<li><a href="#cookies-and-sensitive-headers">9.4. Cookies and Sensitive Headers</a></li>
|
||
<li><a href="#ignored-headers">9.5. Ignored Headers</a></li>
|
||
<li><a href="#management-endpoints">9.6. Management Endpoints</a>
|
||
<ul class="sectlevel3">
|
||
<li><a href="#routes-endpoint">9.6.1. Routes Endpoint</a></li>
|
||
<li><a href="#filters-endpoint">9.6.2. Filters Endpoint</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#strangulation-patterns-and-local-forwards">9.7. Strangulation Patterns and Local Forwards</a></li>
|
||
<li><a href="#uploading-files-through-zuul">9.8. Uploading Files through Zuul</a></li>
|
||
<li><a href="#query-string-encoding">9.9. Query String Encoding</a></li>
|
||
<li><a href="#request-uri-encoding">9.10. Request URI Encoding</a></li>
|
||
<li><a href="#plain-embedded-zuul">9.11. Plain Embedded Zuul</a></li>
|
||
<li><a href="#disable-zuul-filters">9.12. Disable Zuul Filters</a></li>
|
||
<li><a href="#hystrix-fallbacks-for-routes">9.13. Providing Hystrix Fallbacks For Routes</a></li>
|
||
<li><a href="#zuul-timeouts">9.14. Zuul Timeouts</a></li>
|
||
<li><a href="#zuul-redirect-location-rewrite">9.15. Rewriting the <code>Location</code> header</a></li>
|
||
<li><a href="#enabling-cross-origin-requests">9.16. Enabling Cross Origin Requests</a></li>
|
||
<li><a href="#metrics">9.17. Metrics</a></li>
|
||
<li><a href="#zuul-developer-guide">9.18. Zuul Developer Guide</a>
|
||
<ul class="sectlevel3">
|
||
<li><a href="#the-zuul-servlet">9.18.1. The Zuul Servlet</a></li>
|
||
<li><a href="#zuul-requestcontext">9.18.2. Zuul RequestContext</a></li>
|
||
<li><a href="#enablezuulproxy-vs-enablezuulserver">9.18.3. <code>@EnableZuulProxy</code> vs. <code>@EnableZuulServer</code></a></li>
|
||
<li><a href="#zuul-developer-guide-enable-filters">9.18.4. <code>@EnableZuulServer</code> Filters</a></li>
|
||
<li><a href="#enablezuulproxy-filters">9.18.5. <code>@EnableZuulProxy</code> Filters</a></li>
|
||
<li><a href="#custom-zuul-filter-examples">9.18.6. Custom Zuul Filter Examples</a>
|
||
<ul class="sectlevel4">
|
||
<li><a href="#zuul-developer-guide-sample-pre-filter">How to Write a Pre Filter</a></li>
|
||
<li><a href="#zuul-developer-guide-sample-route-filter">How to Write a Route Filter</a></li>
|
||
<li><a href="#zuul-developer-guide-sample-post-filter">How to Write a Post Filter</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#how-zuul-errors-work">9.18.7. How Zuul Errors Work</a></li>
|
||
<li><a href="#zuul-eager-application-context-loading">9.18.8. Zuul Eager Application Context Loading</a></li>
|
||
</ul>
|
||
</li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#polyglot-support-with-sidecar">10. Polyglot support with Sidecar</a></li>
|
||
<li><a href="#retrying-failed-requests">11. Retrying Failed Requests</a>
|
||
<ul class="sectlevel2">
|
||
<li><a href="#backoff-policies">11.1. BackOff Policies</a></li>
|
||
<li><a href="#configuration">11.2. Configuration</a>
|
||
<ul class="sectlevel3">
|
||
<li><a href="#zuul">11.2.1. Zuul</a></li>
|
||
</ul>
|
||
</li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#http-clients">12. HTTP Clients</a></li>
|
||
<li><a href="#modules-in-maintenance-mode">13. Modules In Maintenance Mode</a></li>
|
||
<li><a href="#configuration-properties">14. Configuration properties</a></li>
|
||
</ul>
|
||
</div>
|
||
</div>
|
||
<div id="content">
|
||
<div id="preamble">
|
||
<div class="sectionbody">
|
||
<div class="paragraph">
|
||
<p><strong>2.2.0.RC2</strong></p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>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).</p>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect1">
|
||
<h2 id="service-discovery-eureka-clients"><a class="anchor" href="#service-discovery-eureka-clients"></a><a class="link" href="#service-discovery-eureka-clients">1. Service Discovery: Eureka Clients</a></h2>
|
||
<div class="sectionbody">
|
||
<div class="paragraph">
|
||
<p>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.</p>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="netflix-eureka-client-starter"><a class="anchor" href="#netflix-eureka-client-starter"></a><a class="link" href="#netflix-eureka-client-starter">1.1. How to Include Eureka Client</a></h3>
|
||
<div class="paragraph">
|
||
<p>To include the Eureka Client in your project, use the starter with a group ID of <code>org.springframework.cloud</code> and an artifact ID of <code>spring-cloud-starter-netflix-eureka-client</code>.
|
||
See the <a href="https://projects.spring.io/spring-cloud/">Spring Cloud Project page</a> for details on setting up your build system with the current Spring Cloud Release Train.</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="registering-with-eureka"><a class="anchor" href="#registering-with-eureka"></a><a class="link" href="#registering-with-eureka">1.2. Registering with Eureka</a></h3>
|
||
<div class="paragraph">
|
||
<p>When a client registers with Eureka, it provides meta-data about itself — 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.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The following example shows a minimal Eureka client application:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@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);
|
||
}
|
||
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Note that the preceding example shows a normal <a href="https://projects.spring.io/spring-boot/">Spring Boot</a> application.
|
||
By having <code>spring-cloud-starter-netflix-eureka-client</code> 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:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="title">application.yml</div>
|
||
<div class="content">
|
||
<pre>eureka:
|
||
client:
|
||
serviceUrl:
|
||
defaultZone: http://localhost:8761/eureka/</pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>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).</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The default application name (that is, the service ID), virtual host, and non-secure port (taken from the <code>Environment</code>) are <code>${spring.application.name}</code>, <code>${spring.application.name}</code> and <code>${server.port}</code>, respectively.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Having <code>spring-cloud-starter-netflix-eureka-client</code> on the classpath makes the app into both a Eureka “instance” (that is, it registers itself) and a “client” (it can query the registry to locate other services).
|
||
The instance behaviour is driven by <code>eureka.instance.*</code> configuration keys, but the defaults are fine if you ensure that your application has a value for <code>spring.application.name</code> (this is the default for the Eureka service ID or VIP).</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>See <a href="https://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</a> and <a href="https://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</a> for more details on the configurable options.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>To disable the Eureka Discovery Client, you can set <code>eureka.client.enabled</code> to <code>false</code>. Eureka Discovery Client will also be disabled when <code>spring.cloud.discovery.enabled</code> is set to <code>false</code>.</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="authenticating-with-the-eureka-server"><a class="anchor" href="#authenticating-with-the-eureka-server"></a><a class="link" href="#authenticating-with-the-eureka-server">1.3. Authenticating with the Eureka Server</a></h3>
|
||
<div class="paragraph">
|
||
<p>HTTP basic authentication is automatically added to your eureka client if one of the <code>eureka.client.serviceUrl.defaultZone</code> URLs has credentials embedded in it (curl style, as follows: <code><a href="https://user:password@localhost:8761/eureka" class="bare">user:password@localhost:8761/eureka</a></code>).
|
||
For more complex needs, you can create a <code>@Bean</code> of type <code>DiscoveryClientOptionalArgs</code> and inject <code>ClientFilter</code> instances into it, all of which is applied to the calls from the client to the server.</p>
|
||
</div>
|
||
<div class="admonitionblock note">
|
||
<table>
|
||
<tr>
|
||
<td class="icon">
|
||
<i class="fa icon-note" title="Note"></i>
|
||
</td>
|
||
<td class="content">
|
||
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.
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="status-page-and-health-indicator"><a class="anchor" href="#status-page-and-health-indicator"></a><a class="link" href="#status-page-and-health-indicator">1.4. Status Page and Health Indicator</a></h3>
|
||
<div class="paragraph">
|
||
<p>The status page and health indicators for a Eureka instance default to <code>/info</code> and <code>/health</code> 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 <code>server.servletPath=/custom</code>). The following example shows the default values for the two settings:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="title">application.yml</div>
|
||
<div class="content">
|
||
<pre>eureka:
|
||
instance:
|
||
statusPageUrlPath: ${server.servletPath}/info
|
||
healthCheckUrlPath: ${server.servletPath}/health</pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>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.</p>
|
||
</div>
|
||
<div class="admonitionblock note">
|
||
<table>
|
||
<tr>
|
||
<td class="icon">
|
||
<i class="fa icon-note" title="Note"></i>
|
||
</td>
|
||
<td class="content">
|
||
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.
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="registering-a-secure-application"><a class="anchor" href="#registering-a-secure-application"></a><a class="link" href="#registering-a-secure-application">1.5. Registering a Secure Application</a></h3>
|
||
<div class="paragraph">
|
||
<p>If your app wants to be contacted over HTTPS, you can set two flags in the <code>EurekaInstanceConfig</code>:</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p><code>eureka.instance.[nonSecurePortEnabled]=[false]</code></p>
|
||
</li>
|
||
<li>
|
||
<p><code>eureka.instance.[securePortEnabled]=[true]</code></p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Doing so makes Eureka publish instance information that shows an explicit preference for secure communication.
|
||
The Spring Cloud <code>DiscoveryClient</code> always returns a URI starting with <code>https</code> 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.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>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:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="title">application.yml</div>
|
||
<div class="content">
|
||
<pre>eureka:
|
||
instance:
|
||
statusPageUrl: https://${eureka.hostname}/info
|
||
healthCheckUrl: https://${eureka.hostname}/health
|
||
homePageUrl: https://${eureka.hostname}/</pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>(Note that <code>${eureka.hostname}</code> is a native placeholder only available
|
||
in later versions of Eureka. You could achieve the same thing with
|
||
Spring placeholders as well — for example, by using <code>${eureka.instance.hostName}</code>.)</p>
|
||
</div>
|
||
<div class="admonitionblock note">
|
||
<table>
|
||
<tr>
|
||
<td class="icon">
|
||
<i class="fa icon-note" title="Note"></i>
|
||
</td>
|
||
<td class="content">
|
||
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 “forwarded” 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.
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="eurekas-health-checks"><a class="anchor" href="#eurekas-health-checks"></a><a class="link" href="#eurekas-health-checks">1.6. Eureka’s Health Checks</a></h3>
|
||
<div class="paragraph">
|
||
<p>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:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="title">application.yml</div>
|
||
<div class="content">
|
||
<pre>eureka:
|
||
client:
|
||
healthcheck:
|
||
enabled: true</pre>
|
||
</div>
|
||
</div>
|
||
<div class="admonitionblock warning">
|
||
<table>
|
||
<tr>
|
||
<td class="icon">
|
||
<i class="fa icon-warning" title="Warning"></i>
|
||
</td>
|
||
<td class="content">
|
||
<code>eureka.client.healthcheck.enabled=true</code> should only be set in <code>application.yml</code>. Setting the value in <code>bootstrap.yml</code> causes undesirable side effects, such as registering in Eureka with an <code>UNKNOWN</code> status.
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>If you require more control over the health checks, consider implementing your own <code>com.netflix.appinfo.HealthCheckHandler</code>.</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="eureka-metadata-for-instances-and-clients"><a class="anchor" href="#eureka-metadata-for-instances-and-clients"></a><a class="link" href="#eureka-metadata-for-instances-and-clients">1.7. Eureka Metadata for Instances and Clients</a></h3>
|
||
<div class="paragraph">
|
||
<p>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 <code>eureka.instance.metadataMap</code>, 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.</p>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="using-eureka-on-cloud-foundry"><a class="anchor" href="#using-eureka-on-cloud-foundry"></a><a class="link" href="#using-eureka-on-cloud-foundry">1.7.1. Using Eureka on Cloud Foundry</a></h4>
|
||
<div class="paragraph">
|
||
<p>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 <code>eureka.instance.instanceId</code> is <code>vcap.application.instance_id</code>, as shown in the following example:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="title">application.yml</div>
|
||
<div class="content">
|
||
<pre>eureka:
|
||
instance:
|
||
hostname: ${vcap.application.uris[0]}
|
||
nonSecurePort: 80</pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>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 (<a href="https://run.pivotal.io">PWS</a>).</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="using-eureka-on-aws"><a class="anchor" href="#using-eureka-on-aws"></a><a class="link" href="#using-eureka-on-aws">1.7.2. Using Eureka on AWS</a></h4>
|
||
<div class="paragraph">
|
||
<p>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 <a href="https://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</a> as follows:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@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;
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="changing-the-eureka-instance-id"><a class="anchor" href="#changing-the-eureka-instance-id"></a><a class="link" href="#changing-the-eureka-instance-id">1.7.3. Changing the Eureka Instance ID</a></h4>
|
||
<div class="paragraph">
|
||
<p>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:</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p><code>${spring.cloud.client.hostname}:${spring.application.name}:${spring.application.instance_id:${server.port}}}</code></p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>An example is <code>myhost:myappname:8080</code>.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>By using Spring Cloud, you can override this value by providing a unique identifier in <code>eureka.instance.instanceId</code>, as shown in the following example:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="title">application.yml</div>
|
||
<div class="content">
|
||
<pre>eureka:
|
||
instance:
|
||
instanceId: ${spring.application.name}:${vcap.application.instance_id:${spring.application.instance_id:${random.value}}}</pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>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 <code>vcap.application.instance_id</code> is populated automatically in a Spring Boot application, so the random value is not needed.</p>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="using-the-eurekaclient"><a class="anchor" href="#using-the-eurekaclient"></a><a class="link" href="#using-the-eurekaclient">1.8. Using the EurekaClient</a></h3>
|
||
<div class="paragraph">
|
||
<p>Once you have an application that is a discovery client, you can use it to discover service instances from the <a href="#spring-cloud-eureka-server">Eureka Server</a>.
|
||
One way to do so is to use the native <code>com.netflix.discovery.EurekaClient</code> (as opposed to the Spring Cloud <code>DiscoveryClient</code>), as shown in the following example:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre>@Autowired
|
||
private EurekaClient discoveryClient;
|
||
|
||
public String serviceUrl() {
|
||
InstanceInfo instance = discoveryClient.getNextServerFromEureka("STORES", false);
|
||
return instance.getHomePageUrl();
|
||
}</pre>
|
||
</div>
|
||
</div>
|
||
<div class="admonitionblock tip">
|
||
<table>
|
||
<tr>
|
||
<td class="icon">
|
||
<i class="fa icon-tip" title="Tip"></i>
|
||
</td>
|
||
<td class="content">
|
||
<div class="paragraph">
|
||
<p>Do not use the <code>EurekaClient</code> in a <code>@PostConstruct</code> method or in a <code>@Scheduled</code> method (or anywhere where the <code>ApplicationContext</code> might not be started yet).
|
||
It is initialized in a <code>SmartLifecycle</code> (with <code>phase=0</code>), so the earliest you can rely on it being available is in another <code>SmartLifecycle</code> with a higher phase.</p>
|
||
</div>
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="eurekaclient-without-jersey"><a class="anchor" href="#eurekaclient-without-jersey"></a><a class="link" href="#eurekaclient-without-jersey">1.8.1. EurekaClient without Jersey</a></h4>
|
||
<div class="paragraph">
|
||
<p>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 <code>RestTemplate</code>.
|
||
The following example shows Jersey being excluded:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre><dependency>
|
||
<groupId>org.springframework.cloud</groupId>
|
||
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
|
||
<exclusions>
|
||
<exclusion>
|
||
<groupId>com.sun.jersey</groupId>
|
||
<artifactId>jersey-client</artifactId>
|
||
</exclusion>
|
||
<exclusion>
|
||
<groupId>com.sun.jersey</groupId>
|
||
<artifactId>jersey-core</artifactId>
|
||
</exclusion>
|
||
<exclusion>
|
||
<groupId>com.sun.jersey.contribs</groupId>
|
||
<artifactId>jersey-apache-client4</artifactId>
|
||
</exclusion>
|
||
</exclusions>
|
||
</dependency></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="alternatives-to-the-native-netflix-eurekaclient"><a class="anchor" href="#alternatives-to-the-native-netflix-eurekaclient"></a><a class="link" href="#alternatives-to-the-native-netflix-eurekaclient">1.9. Alternatives to the Native Netflix EurekaClient</a></h3>
|
||
<div class="paragraph">
|
||
<p>You need not use the raw Netflix <code>EurekaClient</code>.
|
||
Also, it is usually more convenient to use it behind a wrapper of some sort.
|
||
Spring Cloud has support for <a href="#spring-cloud-feign">Feign</a> (a REST client builder) and <a href="#spring-cloud-ribbon">Spring <code>RestTemplate</code></a> through the logical Eureka service identifiers (VIPs) instead of physical URLs.
|
||
To configure Ribbon with a fixed list of physical servers, you can set <code><client>.ribbon.listOfServers</code> to a comma-separated list of physical addresses (or hostnames), where <code><client></code> is the ID of the client.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>You can also use the <code>org.springframework.cloud.client.discovery.DiscoveryClient</code>, which provides a simple API (not specific to Netflix) for discovery clients, as shown in the following example:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre>@Autowired
|
||
private DiscoveryClient discoveryClient;
|
||
|
||
public String serviceUrl() {
|
||
List<ServiceInstance> list = discoveryClient.getInstances("STORES");
|
||
if (list != null && list.size() > 0 ) {
|
||
return list.get(0).getUri();
|
||
}
|
||
return null;
|
||
}</pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="why-is-it-so-slow-to-register-a-service"><a class="anchor" href="#why-is-it-so-slow-to-register-a-service"></a><a class="link" href="#why-is-it-so-slow-to-register-a-service">1.10. Why Is It so Slow to Register a Service?</a></h3>
|
||
<div class="paragraph">
|
||
<p>Being an instance also involves a periodic heartbeat to the registry
|
||
(through the client’s <code>serviceUrl</code>) 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 <code>eureka.instance.leaseRenewalIntervalInSeconds</code>.
|
||
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.</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="zones"><a class="anchor" href="#zones"></a><a class="link" href="#zones">1.11. Zones</a></h3>
|
||
<div class="paragraph">
|
||
<p>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.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>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 <a href="#spring-cloud-eureka-server-zones-and-regions">zones and regions</a>
|
||
for more information.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Next, you need to tell Eureka which zone your service is in.
|
||
You can do so by using the <code>metadataMap</code> property.
|
||
For example, if <code>service 1</code> is deployed to both <code>zone 1</code> and <code>zone 2</code>, you need to set the following Eureka properties in <code>service 1</code>:</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p><strong>Service 1 in Zone 1</strong></p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code>eureka.instance.metadataMap.zone = zone1
|
||
eureka.client.preferSameZoneEureka = true</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p><strong>Service 1 in Zone 2</strong></p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code>eureka.instance.metadataMap.zone = zone2
|
||
eureka.client.preferSameZoneEureka = true</code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="refreshing-eureka-clients"><a class="anchor" href="#refreshing-eureka-clients"></a><a class="link" href="#refreshing-eureka-clients">1.12. Refreshing Eureka Clients</a></h3>
|
||
<div class="paragraph">
|
||
<p>By default, the <code>EurekaClient</code> bean is refreshable, meaning the Eureka client properties can be changed and refreshed.
|
||
When a refresh occurs clients will be unregistered from the Eureka server and there might be a brief moment of time
|
||
where all instance of a given service are not available. One way to eliminate this from happening is to disable
|
||
the ability to refresh Eureka clients. To do this set <code>eureka.client.refresh.enable=false</code>.</p>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect1">
|
||
<h2 id="spring-cloud-eureka-server"><a class="anchor" href="#spring-cloud-eureka-server"></a><a class="link" href="#spring-cloud-eureka-server">2. Service Discovery: Eureka Server</a></h2>
|
||
<div class="sectionbody">
|
||
<div class="paragraph">
|
||
<p>This section describes how to set up a Eureka server.</p>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="netflix-eureka-server-starter"><a class="anchor" href="#netflix-eureka-server-starter"></a><a class="link" href="#netflix-eureka-server-starter">2.1. How to Include Eureka Server</a></h3>
|
||
<div class="paragraph">
|
||
<p>To include Eureka Server in your project, use the starter with a group ID of <code>org.springframework.cloud</code> and an artifact ID of <code>spring-cloud-starter-netflix-eureka-server</code>.
|
||
See the <a href="https://projects.spring.io/spring-cloud/">Spring Cloud Project page</a> for details on setting up your build system with the current Spring Cloud Release Train.</p>
|
||
</div>
|
||
<div class="admonitionblock note">
|
||
<table>
|
||
<tr>
|
||
<td class="icon">
|
||
<i class="fa icon-note" title="Note"></i>
|
||
</td>
|
||
<td class="content">
|
||
If your project already uses Thymeleaf as its template engine, the Freemarker templates of the Eureka server may not be loaded correctly. In this case it is necessary to configure the template loader manually:
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="title">application.yml</div>
|
||
<div class="content">
|
||
<pre>spring:
|
||
freemarker:
|
||
template-loader-path: classpath:/templates/
|
||
prefer-file-system-access: false</pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="spring-cloud-running-eureka-server"><a class="anchor" href="#spring-cloud-running-eureka-server"></a><a class="link" href="#spring-cloud-running-eureka-server">2.2. How to Run a Eureka Server</a></h3>
|
||
<div class="paragraph">
|
||
<p>The following example shows a minimal Eureka server:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@SpringBootApplication
|
||
@EnableEurekaServer
|
||
public class Application {
|
||
|
||
public static void main(String[] args) {
|
||
new SpringApplicationBuilder(Application.class).web(true).run(args);
|
||
}
|
||
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The server has a home page with a UI and HTTP API endpoints for the normal Eureka functionality under <code>/eureka/*</code>.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The following links have some Eureka background reading: <a href="https://github.com/cfregly/fluxcapacitor/wiki/NetflixOSS-FAQ#eureka-service-discovery-load-balancer">flux capacitor</a> and <a href="https://groups.google.com/forum/?fromgroups#!topic/eureka_netflix/g3p2r7gHnN0">google group discussion</a>.</p>
|
||
</div>
|
||
<div class="admonitionblock tip">
|
||
<table>
|
||
<tr>
|
||
<td class="icon">
|
||
<i class="fa icon-tip" title="Tip"></i>
|
||
</td>
|
||
<td class="content">
|
||
<div class="paragraph">
|
||
<p>Due to Gradle’s dependency resolution rules and the lack of a parent bom feature, depending on <code>spring-cloud-starter-netflix-eureka-server</code> 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:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="title">build.gradle</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">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}"
|
||
}
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="spring-cloud-eureka-server-zones-and-regions"><a class="anchor" href="#spring-cloud-eureka-server-zones-and-regions"></a><a class="link" href="#spring-cloud-eureka-server-zones-and-regions">2.3. High Availability, Zones and Regions</a></h3>
|
||
<div class="paragraph">
|
||
<p>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).</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>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.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>See also <a href="#spring-cloud-ribbon">below for details of Ribbon support</a> on the client side for Zones and Regions.</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="spring-cloud-eureka-server-standalone-mode"><a class="anchor" href="#spring-cloud-eureka-server-standalone-mode"></a><a class="link" href="#spring-cloud-eureka-server-standalone-mode">2.4. Standalone Mode</a></h3>
|
||
<div class="paragraph">
|
||
<p>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:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="title">application.yml (Standalone Eureka Server)</div>
|
||
<div class="content">
|
||
<pre>server:
|
||
port: 8761
|
||
|
||
eureka:
|
||
instance:
|
||
hostname: localhost
|
||
client:
|
||
registerWithEureka: false
|
||
fetchRegistry: false
|
||
serviceUrl:
|
||
defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/</pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Notice that the <code>serviceUrl</code> is pointing to the same host as the local instance.</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="spring-cloud-eureka-server-peer-awareness"><a class="anchor" href="#spring-cloud-eureka-server-peer-awareness"></a><a class="link" href="#spring-cloud-eureka-server-peer-awareness">2.5. Peer Awareness</a></h3>
|
||
<div class="paragraph">
|
||
<p>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 <code>serviceUrl</code> to a peer, as shown in the following example:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="title">application.yml (Two Peer Aware Eureka Servers)</div>
|
||
<div class="content">
|
||
<pre>---
|
||
spring:
|
||
profiles: peer1
|
||
eureka:
|
||
instance:
|
||
hostname: peer1
|
||
client:
|
||
serviceUrl:
|
||
defaultZone: https://peer2/eureka/
|
||
|
||
---
|
||
spring:
|
||
profiles: peer2
|
||
eureka:
|
||
instance:
|
||
hostname: peer2
|
||
client:
|
||
serviceUrl:
|
||
defaultZone: https://peer1/eureka/</pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>In the preceding example, we have a YAML file that can be used to run the same server on two hosts (<code>peer1</code> and <code>peer2</code>) 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 <code>/etc/hosts</code> to resolve the host names.
|
||
In fact, the <code>eureka.instance.hostname</code> is not needed if you are running on a machine that knows its own hostname (by default, it is looked up by using <code>java.net.InetAddress</code>).</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>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 “split-brain” type failures.
|
||
You can add multiple peers to a system, and as long as they are all
|
||
directly connected to each other, they will synchronize
|
||
the registrations amongst themselves.</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="title">application.yml (Three Peer Aware Eureka Servers)</div>
|
||
<div class="content">
|
||
<pre>eureka:
|
||
client:
|
||
serviceUrl:
|
||
defaultZone: https://peer1/eureka/,http://peer2/eureka/,http://peer3/eureka/
|
||
|
||
---
|
||
spring:
|
||
profiles: peer1
|
||
eureka:
|
||
instance:
|
||
hostname: peer1
|
||
|
||
---
|
||
spring:
|
||
profiles: peer2
|
||
eureka:
|
||
instance:
|
||
hostname: peer2
|
||
|
||
---
|
||
spring:
|
||
profiles: peer3
|
||
eureka:
|
||
instance:
|
||
hostname: peer3</pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="spring-cloud-eureka-server-prefer-ip-address"><a class="anchor" href="#spring-cloud-eureka-server-prefer-ip-address"></a><a class="link" href="#spring-cloud-eureka-server-prefer-ip-address">2.6. When to Prefer IP Address</a></h3>
|
||
<div class="paragraph">
|
||
<p>In some cases, it is preferable for Eureka to advertise the IP addresses of services rather than the hostname.
|
||
Set <code>eureka.instance.preferIpAddress</code> to <code>true</code> and, when the application registers with eureka, it uses its IP address rather than its hostname.</p>
|
||
</div>
|
||
<div class="admonitionblock tip">
|
||
<table>
|
||
<tr>
|
||
<td class="icon">
|
||
<i class="fa icon-tip" title="Tip"></i>
|
||
</td>
|
||
<td class="content">
|
||
<div class="paragraph">
|
||
<p>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 <code>eureka.instance.hostname</code> property.
|
||
You can set your hostname at the run-time by using an environment variable — for example, <code>eureka.instance.hostname=${HOST_NAME}</code>.</p>
|
||
</div>
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="securing-the-eureka-server"><a class="anchor" href="#securing-the-eureka-server"></a><a class="link" href="#securing-the-eureka-server">2.7. Securing The Eureka Server</a></h3>
|
||
<div class="paragraph">
|
||
<p>You can secure your Eureka server simply by adding Spring Security to your
|
||
server’s classpath via <code>spring-boot-starter-security</code>. 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 <code>/eureka/**</code> endpoints.
|
||
For example:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@EnableWebSecurity
|
||
class WebSecurityConfig extends WebSecurityConfigurerAdapter {
|
||
|
||
@Override
|
||
protected void configure(HttpSecurity http) throws Exception {
|
||
http.csrf().ignoringAntMatchers("/eureka/**");
|
||
super.configure(http);
|
||
}
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>For more information on CSRF see the <a href="https://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#csrf">Spring Security documentation</a>.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>A demo Eureka Server can be found in the Spring Cloud Samples <a href="https://github.com/spring-cloud-samples/eureka/tree/Eureka-With-Security">repo</a>.</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="disabling-ribbon-with-eureka-server-and-client-starters"><a class="anchor" href="#disabling-ribbon-with-eureka-server-and-client-starters"></a><a class="link" href="#disabling-ribbon-with-eureka-server-and-client-starters">2.8. Disabling Ribbon with Eureka Server and Client starters</a></h3>
|
||
<div class="paragraph">
|
||
<p><code>spring-cloud-starter-netflix-eureka-server</code> and <code>spring-cloud-starter-netflix-eureka-client</code> come along with
|
||
a <code>spring-cloud-starter-netflix-ribbon</code>. Since Ribbon load-balancer is now in maintenance mode,
|
||
we suggest switching to using the Spring Cloud LoadBalancer, also included in Eureka starters, instead.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>In order to that, you can set the value of <code>spring.cloud.loadbalancer.ribbon.enabled</code> property to <code>false</code>.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>You can then also exclude ribbon-related dependencies from Eureka starters in your build files, like so:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml"><dependency>
|
||
<groupId>org.springframework.cloud</groupId>
|
||
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
|
||
<exclusions>
|
||
<exclusion>
|
||
<groupId>org.springframework.cloud</groupId>
|
||
<artifactId>spring-cloud-starter-ribbon</artifactId>
|
||
</exclusion>
|
||
<exclusion>
|
||
<groupId>com.netflix.ribbon</groupId>
|
||
<artifactId>ribbon-eureka</artifactId>
|
||
</exclusion>
|
||
</exclusions>
|
||
</dependency></code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="jdk-11-support"><a class="anchor" href="#jdk-11-support"></a><a class="link" href="#jdk-11-support">2.9. JDK 11 Support</a></h3>
|
||
<div class="paragraph">
|
||
<p>The JAXB modules which the Eureka server depends upon were removed in JDK 11. If you intend to use JDK 11
|
||
when running a Eureka server you must include these dependencies in your POM or Gradle file.</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml"><dependency>
|
||
<groupId>org.glassfish.jaxb</groupId>
|
||
<artifactId>jaxb-runtime</artifactId>
|
||
</dependency></code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect1">
|
||
<h2 id="circuit-breaker-spring-cloud-circuit-breaker-with-hystrix"><a class="anchor" href="#circuit-breaker-spring-cloud-circuit-breaker-with-hystrix"></a><a class="link" href="#circuit-breaker-spring-cloud-circuit-breaker-with-hystrix">3. Circuit Breaker: Spring Cloud Circuit Breaker With Hystrix</a></h2>
|
||
<div class="sectionbody">
|
||
<div class="sect2">
|
||
<h3 id="disabling-spring-cloud-circuit-breaker-hystrix"><a class="anchor" href="#disabling-spring-cloud-circuit-breaker-hystrix"></a><a class="link" href="#disabling-spring-cloud-circuit-breaker-hystrix">3.1. Disabling Spring Cloud Circuit Breaker Hystrix</a></h3>
|
||
<div class="paragraph">
|
||
<p>You can disable the auto-configuration by setting <code>spring.cloud.circuitbreaker.hystrix.enabled</code>
|
||
to <code>false</code>.</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="configuring-hystrix-circuit-breakers"><a class="anchor" href="#configuring-hystrix-circuit-breakers"></a><a class="link" href="#configuring-hystrix-circuit-breakers">3.2. Configuring Hystrix Circuit Breakers</a></h3>
|
||
<div class="sect3">
|
||
<h4 id="default-configuration"><a class="anchor" href="#default-configuration"></a><a class="link" href="#default-configuration">3.2.1. Default Configuration</a></h4>
|
||
<div class="paragraph">
|
||
<p>To provide a default configuration for all of your circuit breakers create a <code>Customize</code> bean that is passed a
|
||
<code>HystrixCircuitBreakerFactory</code> or <code>ReactiveHystrixCircuitBreakerFactory</code>.
|
||
The <code>configureDefault</code> method can be used to provide a default configuration.</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@Bean
|
||
public Customizer<HystrixCircuitBreakerFactory> defaultConfig() {
|
||
return factory -> factory.configureDefault(id -> HystrixCommand.Setter
|
||
.withGroupKey(HystrixCommandGroupKey.Factory.asKey(id))
|
||
.andCommandPropertiesDefaults(HystrixCommandProperties.Setter()
|
||
.withExecutionTimeoutInMilliseconds(4000)));
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect4">
|
||
<h5 id="reactive-example"><a class="anchor" href="#reactive-example"></a><a class="link" href="#reactive-example">Reactive Example</a></h5>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@Bean
|
||
public Customizer<ReactiveHystrixCircuitBreakerFactory> defaultConfig() {
|
||
return factory -> factory.configureDefault(id -> HystrixObservableCommand.Setter
|
||
.withGroupKey(HystrixCommandGroupKey.Factory.asKey(id))
|
||
.andCommandPropertiesDefaults(HystrixCommandProperties.Setter()
|
||
.withExecutionTimeoutInMilliseconds(4000)));
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="specific-circuit-breaker-configuration"><a class="anchor" href="#specific-circuit-breaker-configuration"></a><a class="link" href="#specific-circuit-breaker-configuration">3.2.2. Specific Circuit Breaker Configuration</a></h4>
|
||
<div class="paragraph">
|
||
<p>Similarly to providing a default configuration, you can create a <code>Customize</code> bean this is passed a
|
||
<code>HystrixCircuitBreakerFactory</code></p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@Bean
|
||
public Customizer<HystrixCircuitBreakerFactory> customizer() {
|
||
return factory -> factory.configure(builder -> builder.commandProperties(
|
||
HystrixCommandProperties.Setter().withExecutionTimeoutInMilliseconds(2000)), "foo", "bar");
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect4">
|
||
<h5 id="reactive-example-2"><a class="anchor" href="#reactive-example-2"></a><a class="link" href="#reactive-example-2">Reactive Example</a></h5>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@Bean
|
||
public Customizer<ReactiveHystrixCircuitBreakerFactory> customizer() {
|
||
return factory -> factory.configure(builder -> builder.commandProperties(
|
||
HystrixCommandProperties.Setter().withExecutionTimeoutInMilliseconds(2000)), "foo", "bar");
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect1">
|
||
<h2 id="circuit-breaker-hystrix-clients"><a class="anchor" href="#circuit-breaker-hystrix-clients"></a><a class="link" href="#circuit-breaker-hystrix-clients">4. Circuit Breaker: Hystrix Clients</a></h2>
|
||
<div class="sectionbody">
|
||
<div class="paragraph">
|
||
<p>Netflix has created a library called <a href="https://github.com/Netflix/Hystrix">Hystrix</a> that implements the <a href="https://martinfowler.com/bliki/CircuitBreaker.html">circuit breaker pattern</a>.
|
||
In a microservice architecture, it is common to have multiple layers of service calls, as shown in the following example:</p>
|
||
</div>
|
||
<div class="imageblock">
|
||
<div class="content">
|
||
<img src="https://raw.githubusercontent.com/spring-cloud/spring-cloud-netflix/master/docs/src/main/asciidoc/images/Hystrix.png" alt="Hystrix">
|
||
</div>
|
||
<div class="title">Figure 1. Microservice Graph</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>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 <code>circuitBreaker.requestVolumeThreshold</code> (default: 20 requests) and the failure percentage is greater than <code>circuitBreaker.errorThresholdPercentage</code> (default: >50%) in a rolling window defined by <code>metrics.rollingStats.timeInMilliseconds</code> (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.</p>
|
||
</div>
|
||
<div class="imageblock">
|
||
<div class="content">
|
||
<img src="https://raw.githubusercontent.com/spring-cloud/spring-cloud-netflix/master/docs/src/main/asciidoc/images/HystrixFallback.png" alt="HystrixFallback">
|
||
</div>
|
||
<div class="title">Figure 2. Hystrix fallback prevents cascading failures</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>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.</p>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="how-to-include-hystrix"><a class="anchor" href="#how-to-include-hystrix"></a><a class="link" href="#how-to-include-hystrix">4.1. How to Include Hystrix</a></h3>
|
||
<div class="paragraph">
|
||
<p>To include Hystrix in your project, use the starter with a group ID of <code>org.springframework.cloud</code>
|
||
and a artifact ID of <code>spring-cloud-starter-netflix-hystrix</code>.
|
||
See the <a href="https://projects.spring.io/spring-cloud/">Spring Cloud Project page</a> for details on setting up your build system with the current Spring Cloud Release Train.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The following example shows a minimal Eureka server with a Hystrix circuit breaker:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre>@SpringBootApplication
|
||
@EnableCircuitBreaker
|
||
public class Application {
|
||
|
||
public static void main(String[] args) {
|
||
new SpringApplicationBuilder(Application.class).web(true).run(args);
|
||
}
|
||
|
||
}
|
||
|
||
@Component
|
||
public class StoreIntegration {
|
||
|
||
@HystrixCommand(fallbackMethod = "defaultStores")
|
||
public Object getStores(Map<String, Object> parameters) {
|
||
//do stuff that might fail
|
||
}
|
||
|
||
public Object defaultStores(Map<String, Object> parameters) {
|
||
return /* something useful */;
|
||
}
|
||
}</pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The <code>@HystrixCommand</code> is provided by a Netflix contrib library called <a href="https://github.com/Netflix/Hystrix/tree/master/hystrix-contrib/hystrix-javanica">“javanica”</a>.
|
||
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.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>To configure the <code>@HystrixCommand</code> you can use the <code>commandProperties</code>
|
||
attribute with a list of <code>@HystrixProperty</code> annotations. See
|
||
<a href="https://github.com/Netflix/Hystrix/tree/master/hystrix-contrib/hystrix-javanica#configuration">here</a>
|
||
for more details. See the <a href="https://github.com/Netflix/Hystrix/wiki/Configuration">Hystrix wiki</a>
|
||
for details on the properties available.</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="netflix-hystrix-starter"><a class="anchor" href="#netflix-hystrix-starter"></a><a class="link" href="#netflix-hystrix-starter">4.2. Propagating the Security Context or Using Spring Scopes</a></h3>
|
||
<div class="paragraph">
|
||
<p>If you want some thread local context to propagate into a <code>@HystrixCommand</code>, 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 “Isolation Strategy”.
|
||
The following example demonstrates setting the thread in the annotation:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@HystrixCommand(fallbackMethod = "stubMyService",
|
||
commandProperties = {
|
||
@HystrixProperty(name="execution.isolation.strategy", value="SEMAPHORE")
|
||
}
|
||
)
|
||
...</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The same thing applies if you are using <code>@SessionScope</code> or <code>@RequestScope</code>.
|
||
If you encounter a runtime exception that says it cannot find the scoped context, you need to use the same thread.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>You also have the option to set the <code>hystrix.shareSecurityContext</code> property to <code>true</code>.
|
||
Doing so auto-configures a Hystrix concurrency strategy plugin hook to transfer the <code>SecurityContext</code> 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 <code>HystrixConcurrencyStrategy</code> as a Spring bean.
|
||
Spring Cloud looks for your implementation within the Spring context and wrap it inside its own plugin.</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="health-indicator"><a class="anchor" href="#health-indicator"></a><a class="link" href="#health-indicator">4.3. Health Indicator</a></h3>
|
||
<div class="paragraph">
|
||
<p>The state of the connected circuit breakers are also exposed in the <code>/health</code> endpoint of the calling application, as shown in the following example:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-json hljs" data-lang="json">{
|
||
"hystrix": {
|
||
"openCircuitBreakers": [
|
||
"StoreIntegration::getStoresByLocationLink"
|
||
],
|
||
"status": "CIRCUIT_OPEN"
|
||
},
|
||
"status": "UP"
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="hystrix-metrics-stream"><a class="anchor" href="#hystrix-metrics-stream"></a><a class="link" href="#hystrix-metrics-stream">4.4. Hystrix Metrics Stream</a></h3>
|
||
<div class="paragraph">
|
||
<p>To enable the Hystrix metrics stream, include a dependency on <code>spring-boot-starter-actuator</code> and set
|
||
<code>management.endpoints.web.exposure.include: hystrix.stream</code>.
|
||
Doing so exposes the <code>/actuator/hystrix.stream</code> as a management endpoint, as shown in the following example:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml"> <dependency>
|
||
<groupId>org.springframework.boot</groupId>
|
||
<artifactId>spring-boot-starter-actuator</artifactId>
|
||
</dependency></code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect1">
|
||
<h2 id="circuit-breaker-hystrix-dashboard"><a class="anchor" href="#circuit-breaker-hystrix-dashboard"></a><a class="link" href="#circuit-breaker-hystrix-dashboard">5. Circuit Breaker: Hystrix Dashboard</a></h2>
|
||
<div class="sectionbody">
|
||
<div class="paragraph">
|
||
<p>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.</p>
|
||
</div>
|
||
<div class="imageblock">
|
||
<div class="content">
|
||
<img src="https://raw.githubusercontent.com/spring-cloud/spring-cloud-netflix/master/docs/src/main/asciidoc/images/Hystrix.png" alt="Hystrix">
|
||
</div>
|
||
<div class="title">Figure 3. Hystrix Dashboard</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect1">
|
||
<h2 id="hystrix-timeouts-and-ribbon-clients"><a class="anchor" href="#hystrix-timeouts-and-ribbon-clients"></a><a class="link" href="#hystrix-timeouts-and-ribbon-clients">6. Hystrix Timeouts And Ribbon Clients</a></h2>
|
||
<div class="sectionbody">
|
||
<div class="paragraph">
|
||
<p>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.</p>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="netflix-hystrix-dashboard-starter"><a class="anchor" href="#netflix-hystrix-dashboard-starter"></a><a class="link" href="#netflix-hystrix-dashboard-starter">6.1. How to Include the Hystrix Dashboard</a></h3>
|
||
<div class="paragraph">
|
||
<p>To include the Hystrix Dashboard in your project, use the starter with a group ID of <code>org.springframework.cloud</code> and an artifact ID of <code>spring-cloud-starter-netflix-hystrix-dashboard</code>.
|
||
See the <a href="https://projects.spring.io/spring-cloud/">Spring Cloud Project page</a> for details on setting up your build system with the current Spring Cloud Release Train.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>To run the Hystrix Dashboard, annotate your Spring Boot main class with <code>@EnableHystrixDashboard</code>.
|
||
Then visit <code>/hystrix</code> and point the dashboard to an individual instance’s <code>/hystrix.stream</code> endpoint in a Hystrix client application.</p>
|
||
</div>
|
||
<div class="admonitionblock note">
|
||
<table>
|
||
<tr>
|
||
<td class="icon">
|
||
<i class="fa icon-note" title="Note"></i>
|
||
</td>
|
||
<td class="content">
|
||
When connecting to a <code>/hystrix.stream</code> 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.
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="turbine"><a class="anchor" href="#turbine"></a><a class="link" href="#turbine">6.2. Turbine</a></h3>
|
||
<div class="paragraph">
|
||
<p>Looking at an individual instance’s Hystrix data is not very useful in terms of the overall health of the system. <a href="https://github.com/Netflix/Turbine">Turbine</a> is an application that aggregates all of the relevant <code>/hystrix.stream</code> endpoints into a combined <code>/turbine.stream</code> for use in the Hystrix Dashboard.
|
||
Individual instances are located through Eureka.
|
||
Running Turbine requires annotating your main class with the <code>@EnableTurbine</code> annotation (for example, by using spring-cloud-starter-netflix-turbine to set up the classpath).
|
||
All of the documented configuration properties from <a href="https://github.com/Netflix/Turbine/wiki/Configuration-(1.x)">the Turbine 1 wiki</a> apply.
|
||
The only difference is that the <code>turbine.instanceUrlSuffix</code> does not need the port prepended, as this is handled automatically unless <code>turbine.instanceInsertPort=false</code>.</p>
|
||
</div>
|
||
<div class="admonitionblock note">
|
||
<table>
|
||
<tr>
|
||
<td class="icon">
|
||
<i class="fa icon-note" title="Note"></i>
|
||
</td>
|
||
<td class="content">
|
||
By default, Turbine looks for the <code>/hystrix.stream</code> endpoint on a registered instance by looking up its <code>hostName</code> and <code>port</code> entries in Eureka and then appending <code>/hystrix.stream</code> to it.
|
||
If the instance’s metadata contains <code>management.port</code>, it is used instead of the <code>port</code> value for the <code>/hystrix.stream</code> endpoint.
|
||
By default, the metadata entry called <code>management.port</code> is equal to the <code>management.port</code> configuration property.
|
||
It can be overridden though with following configuration:
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre>eureka:
|
||
instance:
|
||
metadata-map:
|
||
management.port: ${management.port:8081}</pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The <code>turbine.appConfig</code> 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:</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p><code><a href="https://my.turbine.server:8080/turbine.stream?cluster=CLUSTERNAME" class="bare">my.turbine.server:8080/turbine.stream?cluster=CLUSTERNAME</a></code></p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The cluster parameter can be omitted if the name is <code>default</code>.
|
||
The <code>cluster</code> parameter must match an entry in <code>turbine.aggregator.clusterConfig</code>.
|
||
Values returned from Eureka are upper-case. Consequently, the following example works if there is an application called <code>customers</code> registered with Eureka:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre>turbine:
|
||
aggregator:
|
||
clusterConfig: CUSTOMERS
|
||
appConfig: customers</pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>If you need to customize which cluster names should be used by Turbine (because you do not want to store cluster names in
|
||
<code>turbine.aggregator.clusterConfig</code> configuration), provide a bean of type <code>TurbineClustersProvider</code>.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The <code>clusterName</code> can be customized by a SPEL expression in <code>turbine.clusterNameExpression</code> with root as an instance of <code>InstanceInfo</code>.
|
||
The default value is <code>appName</code>, which means that the Eureka <code>serviceId</code> becomes the cluster key (that is, the <code>InstanceInfo</code> for customers has an <code>appName</code> of <code>CUSTOMERS</code>).
|
||
A different example is <code>turbine.clusterNameExpression=aSGName</code>, which gets the cluster name from the AWS ASG name.
|
||
The following listing shows another example:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre>turbine:
|
||
aggregator:
|
||
clusterConfig: SYSTEM,USER
|
||
appConfig: customers,stores,ui,admin
|
||
clusterNameExpression: metadata['cluster']</pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>In the preceding example, the cluster name from four services is pulled from their metadata map and is expected to have values that include <code>SYSTEM</code> and <code>USER</code>.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>To use the “default” cluster for all apps, you need a string literal expression (with single quotes and escaped with double quotes if it is in YAML as well):</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre>turbine:
|
||
appConfig: customers,stores
|
||
clusterNameExpression: "'default'"</pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Spring Cloud provides a <code>spring-cloud-starter-netflix-turbine</code> that has all the dependencies you need to get a Turbine server running. To add Turbine, create a Spring Boot application and annotate it with <code>@EnableTurbine</code>.</p>
|
||
</div>
|
||
<div class="admonitionblock note">
|
||
<table>
|
||
<tr>
|
||
<td class="icon">
|
||
<i class="fa icon-note" title="Note"></i>
|
||
</td>
|
||
<td class="content">
|
||
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 <em>not</em> allow multiple processes per host, per cluster (the key to the instance ID is the hostname), set <code>turbine.combineHostPort=false</code>.
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="clusters-endpoint"><a class="anchor" href="#clusters-endpoint"></a><a class="link" href="#clusters-endpoint">6.2.1. Clusters Endpoint</a></h4>
|
||
<div class="paragraph">
|
||
<p>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 <code>/clusters</code> endpoint which will return a JSON array of
|
||
all the configured clusters.</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="title">GET /clusters</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-json hljs" data-lang="json">[
|
||
{
|
||
"name": "RACES",
|
||
"link": "http://localhost:8383/turbine.stream?cluster=RACES"
|
||
},
|
||
{
|
||
"name": "WEB",
|
||
"link": "http://localhost:8383/turbine.stream?cluster=WEB"
|
||
}
|
||
]</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>This endpoint can be disabled by setting <code>turbine.endpoints.clusters.enabled</code> to <code>false</code>.</p>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="turbine-stream"><a class="anchor" href="#turbine-stream"></a><a class="link" href="#turbine-stream">6.3. Turbine Stream</a></h3>
|
||
<div class="paragraph">
|
||
<p>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 <code>spring-cloud-netflix-hystrix-stream</code> and the <code>spring-cloud-starter-stream-*</code> of your choice.
|
||
See the <a href="https://docs.spring.io/spring-cloud-stream/docs/current/reference/htmlsingle/">Spring Cloud Stream documentation</a> for details on the brokers and how to configure the client credentials. It should work out of the box for a local broker.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>On the server side, create a Spring Boot application and annotate it with <code>@EnableTurbineStream</code>.
|
||
The Turbine Stream server requires the use of Spring Webflux, therefore <code>spring-boot-starter-webflux</code> needs to be included in your project.
|
||
By default <code>spring-boot-starter-webflux</code> is included when adding <code>spring-cloud-starter-netflix-turbine-stream</code> to your application.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>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 <code><a href="https://myhost:8989" class="bare">myhost:8989</a></code> in the stream input field in the Hystrix Dashboard.
|
||
Circuits are prefixed by their respective <code>serviceId</code>, followed by a dot (<code>.</code>), and then the circuit name.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Spring Cloud provides a <code>spring-cloud-starter-netflix-turbine-stream</code> that has all the dependencies you need to get a Turbine Stream server running.
|
||
You can then add the Stream binder of your choice — such as <code>spring-cloud-starter-stream-rabbit</code>.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Turbine Stream server also supports the <code>cluster</code> parameter.
|
||
Unlike Turbine server, Turbine Stream uses eureka serviceIds as cluster names and these are not configurable.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>If Turbine Stream server is running on port 8989 on <code>my.turbine.server</code> and you have two eureka serviceIds <code>customers</code> and <code>products</code> in your environment, the following URLs will be available on your Turbine Stream server. <code>default</code> and empty cluster name will provide all metrics that Turbine Stream server receives.</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre>https://my.turbine.sever:8989/turbine.stream?cluster=customers
|
||
https://my.turbine.sever:8989/turbine.stream?cluster=products
|
||
https://my.turbine.sever:8989/turbine.stream?cluster=default
|
||
https://my.turbine.sever:8989/turbine.stream</pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>So, you can use eureka serviceIds as cluster names for your Turbine dashboard (or any compatible dashboard).
|
||
You don’t need to configure any properties like <code>turbine.appConfig</code>, <code>turbine.clusterNameExpression</code> and <code>turbine.aggregator.clusterConfig</code> for your Turbine Stream server.</p>
|
||
</div>
|
||
<div class="admonitionblock note">
|
||
<table>
|
||
<tr>
|
||
<td class="icon">
|
||
<i class="fa icon-note" title="Note"></i>
|
||
</td>
|
||
<td class="content">
|
||
Turbine Stream server gathers all metrics from the configured input channel with Spring Cloud Stream. It means that it doesn’t gather Hystrix metrics actively from each instance. It just can provide metrics that were already gathered into the input channel by each instance.
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect1">
|
||
<h2 id="spring-cloud-ribbon"><a class="anchor" href="#spring-cloud-ribbon"></a><a class="link" href="#spring-cloud-ribbon">7. Client Side Load Balancer: Ribbon</a></h2>
|
||
<div class="sectionbody">
|
||
<div class="paragraph">
|
||
<p>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 <code>@FeignClient</code>, this section also applies.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>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 <code>@FeignClient</code> annotation).
|
||
On demand, Spring Cloud creates a new ensemble as an <code>ApplicationContext</code> for each named client by using
|
||
<code>RibbonClientConfiguration</code>.
|
||
This contains (amongst other things) an <code>ILoadBalancer</code>, a <code>RestClient</code>, and a <code>ServerListFilter</code>.</p>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="netflix-ribbon-starter"><a class="anchor" href="#netflix-ribbon-starter"></a><a class="link" href="#netflix-ribbon-starter">7.1. How to Include Ribbon</a></h3>
|
||
<div class="paragraph">
|
||
<p>To include Ribbon in your project, use the starter with a group ID of <code>org.springframework.cloud</code> and an artifact ID of <code>spring-cloud-starter-netflix-ribbon</code>.
|
||
See the <a href="https://projects.spring.io/spring-cloud/">Spring Cloud Project page</a> for details on setting up your build system with the current Spring Cloud Release Train.</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="customizing-the-ribbon-client"><a class="anchor" href="#customizing-the-ribbon-client"></a><a class="link" href="#customizing-the-ribbon-client">7.2. Customizing the Ribbon Client</a></h3>
|
||
<div class="paragraph">
|
||
<p>You can configure some bits of a Ribbon client by using external properties in <code><client>.ribbon.*</code>, 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 <a href="https://github.com/Netflix/ribbon/blob/master/ribbon-core/src/main/java/com/netflix/client/config/CommonClientConfigKey.java"><code>CommonClientConfigKey</code></a> (part of ribbon-core).</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Spring Cloud also lets you take full control of the client by declaring additional configuration (on top of the <code>RibbonClientConfiguration</code>) using <code>@RibbonClient</code>, as shown in the following example:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@Configuration
|
||
@RibbonClient(name = "custom", configuration = CustomConfiguration.class)
|
||
public class TestConfiguration {
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>In this case, the client is composed from the components already in <code>RibbonClientConfiguration</code>, together with any in <code>CustomConfiguration</code> (where the latter generally overrides the former).</p>
|
||
</div>
|
||
<div class="admonitionblock warning">
|
||
<table>
|
||
<tr>
|
||
<td class="icon">
|
||
<i class="fa icon-warning" title="Warning"></i>
|
||
</td>
|
||
<td class="content">
|
||
The <code>CustomConfiguration</code> clas must be a <code>@Configuration</code> class, but take care that it is not in a <code>@ComponentScan</code> for the main application context.
|
||
Otherwise, it is shared by all the <code>@RibbonClients</code>. If you use <code>@ComponentScan</code> (or <code>@SpringBootApplication</code>), 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 <code>@ComponentScan</code>).
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The following table shows the beans that Spring Cloud Netflix provides by default for Ribbon:</p>
|
||
</div>
|
||
<table class="tableblock frame-topbot grid-all" style="width: 60%;">
|
||
<colgroup>
|
||
<col style="width: 33.3333%;">
|
||
<col style="width: 33.3333%;">
|
||
<col style="width: 33.3334%;">
|
||
</colgroup>
|
||
<thead>
|
||
<tr>
|
||
<th class="tableblock halign-center valign-top">Bean Type</th>
|
||
<th class="tableblock halign-center valign-top">Bean Name</th>
|
||
<th class="tableblock halign-center valign-top">Class Name</th>
|
||
</tr>
|
||
</thead>
|
||
<tbody>
|
||
<tr>
|
||
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>IClientConfig</code></p></td>
|
||
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>ribbonClientConfig</code></p></td>
|
||
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>DefaultClientConfigImpl</code></p></td>
|
||
</tr>
|
||
<tr>
|
||
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>IRule</code></p></td>
|
||
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>ribbonRule</code></p></td>
|
||
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>ZoneAvoidanceRule</code></p></td>
|
||
</tr>
|
||
<tr>
|
||
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>IPing</code></p></td>
|
||
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>ribbonPing</code></p></td>
|
||
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>DummyPing</code></p></td>
|
||
</tr>
|
||
<tr>
|
||
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>ServerList<Server></code></p></td>
|
||
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>ribbonServerList</code></p></td>
|
||
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>ConfigurationBasedServerList</code></p></td>
|
||
</tr>
|
||
<tr>
|
||
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>ServerListFilter<Server></code></p></td>
|
||
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>ribbonServerListFilter</code></p></td>
|
||
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>ZonePreferenceServerListFilter</code></p></td>
|
||
</tr>
|
||
<tr>
|
||
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>ILoadBalancer</code></p></td>
|
||
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>ribbonLoadBalancer</code></p></td>
|
||
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>ZoneAwareLoadBalancer</code></p></td>
|
||
</tr>
|
||
<tr>
|
||
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>ServerListUpdater</code></p></td>
|
||
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>ribbonServerListUpdater</code></p></td>
|
||
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>PollingServerListUpdater</code></p></td>
|
||
</tr>
|
||
</tbody>
|
||
</table>
|
||
<div class="paragraph">
|
||
<p>Creating a bean of one of those type and placing it in a <code>@RibbonClient</code> configuration (such as <code>FooConfiguration</code> above) lets you override each one of the beans described, as shown in the following example:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@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();
|
||
}
|
||
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The include statement in the preceding example replaces <code>NoOpPing</code> with <code>PingUrl</code> and provides a custom <code>serverListFilter</code>.</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="customizing-the-default-for-all-ribbon-clients"><a class="anchor" href="#customizing-the-default-for-all-ribbon-clients"></a><a class="link" href="#customizing-the-default-for-all-ribbon-clients">7.3. Customizing the Default for All Ribbon Clients</a></h3>
|
||
<div class="paragraph">
|
||
<p>A default configuration can be provided for all Ribbon Clients by using the <code>@RibbonClients</code> annotation and registering a default configuration, as shown in the following example:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@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<Server> ribbonServerList(IClientConfig config) {
|
||
return new RibbonClientDefaultConfigurationTestsConfig.BazServiceList(config);
|
||
}
|
||
|
||
@Bean
|
||
public ServerListSubsetFilter serverListFilter() {
|
||
ServerListSubsetFilter filter = new ServerListSubsetFilter();
|
||
return filter;
|
||
}
|
||
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="customizing-the-ribbon-client-by-setting-properties"><a class="anchor" href="#customizing-the-ribbon-client-by-setting-properties"></a><a class="link" href="#customizing-the-ribbon-client-by-setting-properties">7.4. Customizing the Ribbon Client by Setting Properties</a></h3>
|
||
<div class="paragraph">
|
||
<p>Starting with version 1.2.0, Spring Cloud Netflix now supports customizing Ribbon clients by setting properties to be compatible with the <a href="https://github.com/Netflix/ribbon/wiki/Working-with-load-balancers#components-of-load-balancer">Ribbon documentation</a>.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>This lets you change behavior at start up time in different environments.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The following list shows the supported properties>:</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p><code><clientName>.ribbon.NFLoadBalancerClassName</code>: Should implement <code>ILoadBalancer</code></p>
|
||
</li>
|
||
<li>
|
||
<p><code><clientName>.ribbon.NFLoadBalancerRuleClassName</code>: Should implement <code>IRule</code></p>
|
||
</li>
|
||
<li>
|
||
<p><code><clientName>.ribbon.NFLoadBalancerPingClassName</code>: Should implement <code>IPing</code></p>
|
||
</li>
|
||
<li>
|
||
<p><code><clientName>.ribbon.NIWSServerListClassName</code>: Should implement <code>ServerList</code></p>
|
||
</li>
|
||
<li>
|
||
<p><code><clientName>.ribbon.NIWSServerListFilterClassName</code>: Should implement <code>ServerListFilter</code></p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
<div class="admonitionblock note">
|
||
<table>
|
||
<tr>
|
||
<td class="icon">
|
||
<i class="fa icon-note" title="Note"></i>
|
||
</td>
|
||
<td class="content">
|
||
Classes defined in these properties have precedence over beans defined by using <code>@RibbonClient(configuration=MyRibbonConfig.class)</code> and the defaults provided by Spring Cloud Netflix.
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>To set the <code>IRule</code> for a service name called <code>users</code>, you could set the following properties:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="title">application.yml</div>
|
||
<div class="content">
|
||
<pre>users:
|
||
ribbon:
|
||
NIWSServerListClassName: com.netflix.loadbalancer.ConfigurationBasedServerList
|
||
NFLoadBalancerRuleClassName: com.netflix.loadbalancer.WeightedResponseTimeRule</pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>See the <a href="https://github.com/Netflix/ribbon/wiki/Working-with-load-balancers">Ribbon documentation</a> for implementations provided by Ribbon.</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="using-ribbon-with-eureka"><a class="anchor" href="#using-ribbon-with-eureka"></a><a class="link" href="#using-ribbon-with-eureka">7.5. Using Ribbon with Eureka</a></h3>
|
||
<div class="paragraph">
|
||
<p>When Eureka is used in conjunction with Ribbon (that is, both are on the classpath), the <code>ribbonServerList</code> is overridden with an extension of <code>DiscoveryEnabledNIWSServerList</code>, which populates the list of servers from Eureka.
|
||
It also replaces the <code>IPing</code> interface with <code>NIWSDiscoveryPing</code>, which delegates to Eureka to determine if a server is up.
|
||
The <code>ServerList</code> that is installed by default is a <code>DomainExtractingServerList</code>. 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 “zone” information, as provided in the instance metadata (so, on the remote clients, set <code>eureka.instance.metadataMap.zone</code>).
|
||
If that is missing and if the <code>approximateZoneFromHostname</code> 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 <code>ServerListFilter</code>.
|
||
By default, it is used to locate a server in the same zone as the client, because the default is a <code>ZonePreferenceServerListFilter</code>.
|
||
By default, the zone of the client is determined in the same way as the remote instances (that is, through <code>eureka.instance.metadataMap.zone</code>).</p>
|
||
</div>
|
||
<div class="admonitionblock note">
|
||
<table>
|
||
<tr>
|
||
<td class="icon">
|
||
<i class="fa icon-note" title="Note"></i>
|
||
</td>
|
||
<td class="content">
|
||
The orthodox “archaius” 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).
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
<div class="admonitionblock note">
|
||
<table>
|
||
<tr>
|
||
<td class="icon">
|
||
<i class="fa icon-note" title="Note"></i>
|
||
</td>
|
||
<td class="content">
|
||
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 <code>eureka.client.availabilityZones</code>, which is a map from region name to a list of zones, and pull out the first zone for the instance’s own region (that is, the <code>eureka.client.region</code>, which defaults to "us-east-1", for compatibility with native Netflix).
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="spring-cloud-ribbon-without-eureka"><a class="anchor" href="#spring-cloud-ribbon-without-eureka"></a><a class="link" href="#spring-cloud-ribbon-without-eureka">7.6. Example: How to Use Ribbon Without Eureka</a></h3>
|
||
<div class="paragraph">
|
||
<p>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 <code>@RibbonClient</code> 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:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="title">application.yml</div>
|
||
<div class="content">
|
||
<pre>stores:
|
||
ribbon:
|
||
listOfServers: example.com,google.com</pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="example-disable-eureka-use-in-ribbon"><a class="anchor" href="#example-disable-eureka-use-in-ribbon"></a><a class="link" href="#example-disable-eureka-use-in-ribbon">7.7. Example: Disable Eureka Use in Ribbon</a></h3>
|
||
<div class="paragraph">
|
||
<p>Setting the <code>ribbon.eureka.enabled</code> property to <code>false</code> explicitly disables the use of Eureka in Ribbon, as shown in the following example:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="title">application.yml</div>
|
||
<div class="content">
|
||
<pre>ribbon:
|
||
eureka:
|
||
enabled: false</pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="using-the-ribbon-api-directly"><a class="anchor" href="#using-the-ribbon-api-directly"></a><a class="link" href="#using-the-ribbon-api-directly">7.8. Using the Ribbon API Directly</a></h3>
|
||
<div class="paragraph">
|
||
<p>You can also use the <code>LoadBalancerClient</code> directly, as shown in the following example:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">public class MyClass {
|
||
@Autowired
|
||
private LoadBalancerClient loadBalancer;
|
||
|
||
public void doStuff() {
|
||
ServiceInstance instance = loadBalancer.choose("stores");
|
||
URI storesUri = URI.create(String.format("https://%s:%s", instance.getHost(), instance.getPort()));
|
||
// ... do something with the URI
|
||
}
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="ribbon-child-context-eager-load"><a class="anchor" href="#ribbon-child-context-eager-load"></a><a class="link" href="#ribbon-child-context-eager-load">7.9. Caching of Ribbon Configuration</a></h3>
|
||
<div class="paragraph">
|
||
<p>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:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="title">application.yml</div>
|
||
<div class="content">
|
||
<pre>ribbon:
|
||
eager-load:
|
||
enabled: true
|
||
clients: client1, client2, client3</pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="how-to-configure-hystrix-thread-pools"><a class="anchor" href="#how-to-configure-hystrix-thread-pools"></a><a class="link" href="#how-to-configure-hystrix-thread-pools">7.10. How to Configure Hystrix Thread Pools</a></h3>
|
||
<div class="paragraph">
|
||
<p>If you change <code>zuul.ribbonIsolationStrategy</code> to <code>THREAD</code>, the thread isolation strategy for Hystrix is used for all routes.
|
||
In that case, the <code>HystrixThreadPoolKey</code> is set to <code>RibbonCommand</code> 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:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="title">application.yml</div>
|
||
<div class="content">
|
||
<pre>zuul:
|
||
threadPool:
|
||
useSeparateThreadPools: true</pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The preceding example results in HystrixCommands being executed in the Hystrix thread pool for each route.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>In this case, the default <code>HystrixThreadPoolKey</code> is the same as the service ID for each route.
|
||
To add a prefix to <code>HystrixThreadPoolKey</code>, set <code>zuul.threadPool.threadPoolKeyPrefix</code> to the value that you want to add, as shown in the following example:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="title">application.yml</div>
|
||
<div class="content">
|
||
<pre>zuul:
|
||
threadPool:
|
||
useSeparateThreadPools: true
|
||
threadPoolKeyPrefix: zuulgw</pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="how-to-provdie-a-key-to-ribbon"><a class="anchor" href="#how-to-provdie-a-key-to-ribbon"></a><a class="link" href="#how-to-provdie-a-key-to-ribbon">7.11. How to Provide a Key to Ribbon’s <code>IRule</code></a></h3>
|
||
<div class="paragraph">
|
||
<p>If you need to provide your own <code>IRule</code> implementation to handle a special routing requirement like a “canary” test, pass some information to the <code>choose</code> method of <code>IRule</code>.</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="title">com.netflix.loadbalancer.IRule.java</div>
|
||
<div class="content">
|
||
<pre>public interface IRule{
|
||
public Server choose(Object key);
|
||
:</pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>You can provide some information that is used by your <code>IRule</code> implementation to choose a target server, as shown in the following example:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre>RequestContext.getCurrentContext()
|
||
.set(FilterConstants.LOAD_BALANCER_KEY, "canary-test");</pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>If you put any object into the <code>RequestContext</code> with a key of <code>FilterConstants.LOAD_BALANCER_KEY</code>, it is passed to the <code>choose</code> method of the <code>IRule</code> implementation.
|
||
The code shown in the preceding example must be executed before <code>RibbonRoutingFilter</code> is executed.
|
||
Zuul’s pre filter is the best place to do that.
|
||
You can access HTTP headers and query parameters through the <code>RequestContext</code> in pre filter, so it can be used to determine the <code>LOAD_BALANCER_KEY</code> that is passed to Ribbon.
|
||
If you do not put any value with <code>LOAD_BALANCER_KEY</code> in <code>RequestContext</code>, null is passed as a parameter of the <code>choose</code> method.</p>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect1">
|
||
<h2 id="external-configuration-archaius"><a class="anchor" href="#external-configuration-archaius"></a><a class="link" href="#external-configuration-archaius">8. External Configuration: Archaius</a></h2>
|
||
<div class="sectionbody">
|
||
<div class="paragraph">
|
||
<p><a href="https://github.com/Netflix/archaius">Archaius</a> 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 <a href="https://commons.apache.org/proper/commons-configuration">Apache Commons Configuration</a> 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<Type>Property classes as handles to properties, as shown in the following example:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="title">Archaius Example</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">class ArchaiusTest {
|
||
DynamicStringProperty myprop = DynamicPropertyFactory
|
||
.getInstance()
|
||
.getStringProperty("my.prop");
|
||
|
||
void doSomething() {
|
||
OtherClass.someMethod(myprop.get());
|
||
}
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>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).</p>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect1">
|
||
<h2 id="router-and-filter-zuul"><a class="anchor" href="#router-and-filter-zuul"></a><a class="link" href="#router-and-filter-zuul">9. Router and Filter: Zuul</a></h2>
|
||
<div class="sectionbody">
|
||
<div class="paragraph">
|
||
<p>Routing is an integral part of a microservice architecture.
|
||
For example, <code>/</code> may be mapped to your web application, <code>/api/users</code> is mapped to the user service and <code>/api/shop</code> is mapped to the shop service.
|
||
<a href="https://github.com/Netflix/zuul">Zuul</a> is a JVM-based router and server-side load balancer from Netflix.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p><a href="https://www.slideshare.net/MikeyCohen1/edge-architecture-ieee-international-conference-on-cloud-engineering-32240146/27">Netflix uses Zuul</a> for the following:</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p>Authentication</p>
|
||
</li>
|
||
<li>
|
||
<p>Insights</p>
|
||
</li>
|
||
<li>
|
||
<p>Stress Testing</p>
|
||
</li>
|
||
<li>
|
||
<p>Canary Testing</p>
|
||
</li>
|
||
<li>
|
||
<p>Dynamic Routing</p>
|
||
</li>
|
||
<li>
|
||
<p>Service Migration</p>
|
||
</li>
|
||
<li>
|
||
<p>Load Shedding</p>
|
||
</li>
|
||
<li>
|
||
<p>Security</p>
|
||
</li>
|
||
<li>
|
||
<p>Static Response handling</p>
|
||
</li>
|
||
<li>
|
||
<p>Active/Active traffic management</p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Zuul’s rule engine lets rules and filters be written in essentially any JVM language, with built-in support for Java and Groovy.</p>
|
||
</div>
|
||
<div class="admonitionblock note">
|
||
<table>
|
||
<tr>
|
||
<td class="icon">
|
||
<i class="fa icon-note" title="Note"></i>
|
||
</td>
|
||
<td class="content">
|
||
The configuration property <code>zuul.max.host.connections</code> has been replaced by two new properties, <code>zuul.host.maxTotalConnections</code> and <code>zuul.host.maxPerRouteConnections</code>, which default to 200 and 20 respectively.
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
<div class="admonitionblock note">
|
||
<table>
|
||
<tr>
|
||
<td class="icon">
|
||
<i class="fa icon-note" title="Note"></i>
|
||
</td>
|
||
<td class="content">
|
||
The default Hystrix isolation pattern (<code>ExecutionIsolationStrategy</code>) for all routes is <code>SEMAPHORE</code>.
|
||
<code>zuul.ribbonIsolationStrategy</code> can be changed to <code>THREAD</code> if that isolation pattern is preferred.
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="netflix-zuul-starter"><a class="anchor" href="#netflix-zuul-starter"></a><a class="link" href="#netflix-zuul-starter">9.1. How to Include Zuul</a></h3>
|
||
<div class="paragraph">
|
||
<p>To include Zuul in your project, use the starter with a group ID of <code>org.springframework.cloud</code> and a artifact ID of <code>spring-cloud-starter-netflix-zuul</code>.
|
||
See the <a href="https://projects.spring.io/spring-cloud/">Spring Cloud Project page</a> for details on setting up your build system with the current Spring Cloud Release Train.</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="netflix-zuul-reverse-proxy"><a class="anchor" href="#netflix-zuul-reverse-proxy"></a><a class="link" href="#netflix-zuul-reverse-proxy">9.2. Embedded Zuul Reverse Proxy</a></h3>
|
||
<div class="paragraph">
|
||
<p>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.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>To enable it, annotate a Spring Boot main class with <code>@EnableZuulProxy</code>. Doing so causes local calls to be forwarded to the appropriate service.
|
||
By convention, a service with an ID of <code>users</code> receives requests from the proxy located at <code>/users</code> (with the prefix stripped).
|
||
The proxy uses Ribbon to locate an instance to which to forward through discovery.
|
||
All requests are executed in a <a href="#hystrix-fallbacks-for-routes">hystrix command</a>, so failures appear in Hystrix metrics.
|
||
Once the circuit is open, the proxy does not try to contact the service.</p>
|
||
</div>
|
||
<div class="admonitionblock note">
|
||
<table>
|
||
<tr>
|
||
<td class="icon">
|
||
<i class="fa icon-note" title="Note"></i>
|
||
</td>
|
||
<td class="content">
|
||
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).
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>To skip having a service automatically added, set <code>zuul.ignored-services</code> 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:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="title">application.yml</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-yaml hljs" data-lang="yaml"> zuul:
|
||
ignoredServices: '*'
|
||
routes:
|
||
users: /myusers/**</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>In the preceding example, all services are ignored, <strong>except</strong> for <code>users</code>.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>To augment or change the proxy routes, you can add external configuration, as follows:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="title">application.yml</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-yaml hljs" data-lang="yaml"> zuul:
|
||
routes:
|
||
users: /myusers/**</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The preceding example means that HTTP calls to <code>/myusers</code> get forwarded to the <code>users</code> service (for example <code>/myusers/101</code> is forwarded to <code>/101</code>).</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>To get more fine-grained control over a route, you can specify the path and the serviceId independently, as follows:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="title">application.yml</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-yaml hljs" data-lang="yaml"> zuul:
|
||
routes:
|
||
users:
|
||
path: /myusers/**
|
||
serviceId: users_service</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The preceding example means that HTTP calls to <code>/myusers</code> get forwarded to the <code>users_service</code> service.
|
||
The route must have a <code>path</code> that can be specified as an ant-style pattern, so <code>/myusers/*</code> only matches one level, but <code>/myusers/**</code> matches hierarchically.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The location of the back end can be specified as either a <code>serviceId</code> (for a service from discovery) or a <code>url</code> (for a physical location), as shown in the following example:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="title">application.yml</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-yaml hljs" data-lang="yaml"> zuul:
|
||
routes:
|
||
users:
|
||
path: /myusers/**
|
||
url: https://example.com/users_service</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>These simple url-routes do not get executed as a <code>HystrixCommand</code>, nor do they load-balance multiple URLs with Ribbon.
|
||
To achieve those goals, you can specify a <code>serviceId</code> with a static list of servers, as follows:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="title">application.yml</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-yaml hljs" data-lang="yaml">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: https://example1.com,http://example2.com
|
||
ConnectTimeout: 1000
|
||
ReadTimeout: 3000
|
||
MaxTotalHttpConnections: 500
|
||
MaxConnectionsPerHost: 100</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Another method is specifiying a service-route and configuring a Ribbon client for the <code>serviceId</code> (doing so requires disabling Eureka support in Ribbon — see <a href="#spring-cloud-ribbon-without-eureka">above for more information</a>), as shown in the following example:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="title">application.yml</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-yaml hljs" data-lang="yaml">zuul:
|
||
routes:
|
||
users:
|
||
path: /myusers/**
|
||
serviceId: users
|
||
|
||
ribbon:
|
||
eureka:
|
||
enabled: false
|
||
|
||
users:
|
||
ribbon:
|
||
listOfServers: example.com,google.com</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>You can provide a convention between <code>serviceId</code> and routes by using <code>regexmapper</code>.
|
||
It uses regular-expression named groups to extract variables from <code>serviceId</code> and inject them into a route pattern, as shown in the following example:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="title">ApplicationConfiguration.java</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@Bean
|
||
public PatternServiceRouteMapper serviceRouteMapper() {
|
||
return new PatternServiceRouteMapper(
|
||
"(?<name>^.+)-(?<version>v.+$)",
|
||
"${version}/${name}");
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The preceding example means that a <code>serviceId</code> of <code>myusers-v1</code> is mapped to route <code>/v1/myusers/**</code>.
|
||
Any regular expression is accepted, but all named groups must be present in both <code>servicePattern</code> and <code>routePattern</code>.
|
||
If <code>servicePattern</code> does not match a <code>serviceId</code>, the default behavior is used.
|
||
In the preceding example, a <code>serviceId</code> of <code>myusers</code> is mapped to the "/myusers/**" route (with no version detected).
|
||
This feature is disabled by default and only applies to discovered services.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>To add a prefix to all mappings, set <code>zuul.prefix</code> to a value, such as <code>/api</code>.
|
||
By default, the proxy prefix is stripped from the request before the request is forwarded by (you can switch this behavior off with <code>zuul.stripPrefix=false</code>).
|
||
You can also switch off the stripping of the service-specific prefix from individual routes, as shown in the following example:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="title">application.yml</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-yaml hljs" data-lang="yaml"> zuul:
|
||
routes:
|
||
users:
|
||
path: /myusers/**
|
||
stripPrefix: false</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="admonitionblock note">
|
||
<table>
|
||
<tr>
|
||
<td class="icon">
|
||
<i class="fa icon-note" title="Note"></i>
|
||
</td>
|
||
<td class="content">
|
||
<code>zuul.stripPrefix</code> only applies to the prefix set in <code>zuul.prefix</code>.
|
||
It does not have any effect on prefixes defined within a given route’s <code>path</code>.
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>In the preceding example, requests to <code>/myusers/101</code> are forwarded to <code>/myusers/101</code> on the <code>users</code> service.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The <code>zuul.routes</code> entries actually bind to an object of type <code>ZuulProperties</code>.
|
||
If you look at the properties of that object, you can see that it also has a <code>retryable</code> flag.
|
||
Set that flag to <code>true</code> to have the Ribbon client automatically retry failed requests.
|
||
You can also set that flag to <code>true</code> when you need to modify the parameters of the retry operations that use the Ribbon client configuration.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>By default, the <code>X-Forwarded-Host</code> header is added to the forwarded requests.
|
||
To turn it off, set <code>zuul.addProxyHeaders = false</code>.
|
||
By default, the prefix path is stripped, and the request to the back end picks up a <code>X-Forwarded-Prefix</code> header (<code>/myusers</code> in the examples shown earlier).</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>If you set a default route (<code>/</code>), an application with <code>@EnableZuulProxy</code> could act as a standalone server. For example, <code>zuul.route.home: /</code> would route all traffic ("/**") to the "home" service.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>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:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="title">application.yml</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-yaml hljs" data-lang="yaml"> zuul:
|
||
ignoredPatterns: /**/admin/**
|
||
routes:
|
||
users: /myusers/**</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The preceding example means that all calls (such as <code>/myusers/101</code>) are forwarded to <code>/101</code> on the <code>users</code> service.
|
||
However, calls including <code>/admin/</code> do not resolve.</p>
|
||
</div>
|
||
<div class="admonitionblock warning">
|
||
<table>
|
||
<tr>
|
||
<td class="icon">
|
||
<i class="fa icon-warning" title="Warning"></i>
|
||
</td>
|
||
<td class="content">
|
||
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:
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="title">application.yml</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-yaml hljs" data-lang="yaml"> zuul:
|
||
routes:
|
||
users:
|
||
path: /myusers/**
|
||
legacy:
|
||
path: /**</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>If you were to use a properties file, the <code>legacy</code> path might end up in front of the <code>users</code>
|
||
path, rendering the <code>users</code> path unreachable.</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="zuul-http-client"><a class="anchor" href="#zuul-http-client"></a><a class="link" href="#zuul-http-client">9.3. Zuul Http Client</a></h3>
|
||
<div class="paragraph">
|
||
<p>The default HTTP client used by Zuul is now backed by the Apache HTTP Client instead of the deprecated Ribbon <code>RestClient</code>.
|
||
To use <code>RestClient</code> or <code>okhttp3.OkHttpClient</code>, set <code>ribbon.restclient.enabled=true</code> or <code>ribbon.okhttp.enabled=true</code>, respectively.
|
||
If you would like to customize the Apache HTTP client or the OK HTTP client, provide a bean of type <code>ClosableHttpClient</code> or <code>OkHttpClient</code>.</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="cookies-and-sensitive-headers"><a class="anchor" href="#cookies-and-sensitive-headers"></a><a class="link" href="#cookies-and-sensitive-headers">9.4. Cookies and Sensitive Headers</a></h3>
|
||
<div class="paragraph">
|
||
<p>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).</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>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) <code>Set-Cookie</code> and <code>Cookie</code> 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.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The sensitive headers can be configured as a comma-separated list per route, as shown in the following example:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="title">application.yml</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-yaml hljs" data-lang="yaml"> zuul:
|
||
routes:
|
||
users:
|
||
path: /myusers/**
|
||
sensitiveHeaders: Cookie,Set-Cookie,Authorization
|
||
url: https://downstream</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="admonitionblock note">
|
||
<table>
|
||
<tr>
|
||
<td class="icon">
|
||
<i class="fa icon-note" title="Note"></i>
|
||
</td>
|
||
<td class="content">
|
||
This is the default value for <code>sensitiveHeaders</code>, 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).
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The <code>sensitiveHeaders</code> are a blacklist, and the default is not empty.
|
||
Consequently, to make Zuul send all headers (except the <code>ignored</code> 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 <code>sensitiveHeaders</code>:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="title">application.yml</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-yaml hljs" data-lang="yaml"> zuul:
|
||
routes:
|
||
users:
|
||
path: /myusers/**
|
||
sensitiveHeaders:
|
||
url: https://downstream</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>You can also set sensitive headers, by setting <code>zuul.sensitiveHeaders</code>.
|
||
If <code>sensitiveHeaders</code> is set on a route, it overrides the global <code>sensitiveHeaders</code> setting.</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="ignored-headers"><a class="anchor" href="#ignored-headers"></a><a class="link" href="#ignored-headers">9.5. Ignored Headers</a></h3>
|
||
<div class="paragraph">
|
||
<p>In addition to the route-sensitive headers, you can set a global value called <code>zuul.ignoredHeaders</code> 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 “security” 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 <code>zuul.ignoreSecurityHeaders</code> to <code>false</code>.
|
||
Doing so can be useful if you disabled the HTTP Security response headers in Spring Security and want the values provided by downstream services.</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="management-endpoints"><a class="anchor" href="#management-endpoints"></a><a class="link" href="#management-endpoints">9.6. Management Endpoints</a></h3>
|
||
<div class="paragraph">
|
||
<p>By default, if you use <code>@EnableZuulProxy</code> with the Spring Boot Actuator, you enable two additional endpoints:</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p>Routes</p>
|
||
</li>
|
||
<li>
|
||
<p>Filters</p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="routes-endpoint"><a class="anchor" href="#routes-endpoint"></a><a class="link" href="#routes-endpoint">9.6.1. Routes Endpoint</a></h4>
|
||
<div class="paragraph">
|
||
<p>A GET to the routes endpoint at <code>/routes</code> returns a list of the mapped routes:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="title">GET /routes</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-json hljs" data-lang="json">{
|
||
/stores/**: "http://localhost:8081"
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Additional route details can be requested by adding the <code>?format=details</code> query string to <code>/routes</code>.
|
||
Doing so produces the following output:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="title">GET /routes/details</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-json hljs" data-lang="json">{
|
||
"/stores/**": {
|
||
"id": "stores",
|
||
"fullPath": "/stores/**",
|
||
"location": "http://localhost:8081",
|
||
"path": "/**",
|
||
"prefix": "/stores",
|
||
"retryable": false,
|
||
"customSensitiveHeaders": false,
|
||
"prefixStripped": true
|
||
}
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>A <code>POST</code> to <code>/routes</code> 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 <code>endpoints.routes.enabled</code> to <code>false</code>.</p>
|
||
</div>
|
||
<div class="admonitionblock note">
|
||
<table>
|
||
<tr>
|
||
<td class="icon">
|
||
<i class="fa icon-note" title="Note"></i>
|
||
</td>
|
||
<td class="content">
|
||
the routes should respond automatically to changes in the service catalog, but the <code>POST</code> to <code>/routes</code> is a way to force the change
|
||
to happen immediately.
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="filters-endpoint"><a class="anchor" href="#filters-endpoint"></a><a class="link" href="#filters-endpoint">9.6.2. Filters Endpoint</a></h4>
|
||
<div class="paragraph">
|
||
<p>A <code>GET</code> to the filters endpoint at <code>/filters</code> 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.</p>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="strangulation-patterns-and-local-forwards"><a class="anchor" href="#strangulation-patterns-and-local-forwards"></a><a class="link" href="#strangulation-patterns-and-local-forwards">9.7. Strangulation Patterns and Local Forwards</a></h3>
|
||
<div class="paragraph">
|
||
<p>A common pattern when migrating an existing application or API is to “strangle” old endpoints, slowly replacing them with different implementations.
|
||
The Zuul proxy is a useful tool for this because you can use it to handle all traffic from the clients of the old endpoints but redirect some of the requests to new ones.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The following example shows the configuration details for a “strangle” scenario:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="title">application.yml</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-yaml hljs" data-lang="yaml"> zuul:
|
||
routes:
|
||
first:
|
||
path: /first/**
|
||
url: https://first.example.com
|
||
second:
|
||
path: /second/**
|
||
url: forward:/second
|
||
third:
|
||
path: /third/**
|
||
url: forward:/3rd
|
||
legacy:
|
||
path: /**
|
||
url: https://legacy.example.com</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>In the preceding example, we are strangle the “legacy” application, which is mapped to all requests that do not match one of the other patterns.
|
||
Paths in <code>/first/**</code> have been extracted into a new service with an external URL.
|
||
Paths in <code>/second/**</code> are forwarded so that they can be handled locally (for example, with a normal Spring <code>@RequestMapping</code>).
|
||
Paths in <code>/third/**</code> are also forwarded but with a different prefix (<code>/third/foo</code> is forwarded to <code>/3rd/foo</code>).</p>
|
||
</div>
|
||
<div class="admonitionblock note">
|
||
<table>
|
||
<tr>
|
||
<td class="icon">
|
||
<i class="fa icon-note" title="Note"></i>
|
||
</td>
|
||
<td class="content">
|
||
The ignored patterns aren’t completely ignored, they just are not handled by the proxy (so they are also effectively forwarded locally).
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="uploading-files-through-zuul"><a class="anchor" href="#uploading-files-through-zuul"></a><a class="link" href="#uploading-files-through-zuul">9.8. Uploading Files through Zuul</a></h3>
|
||
<div class="paragraph">
|
||
<p>If you use <code>@EnableZuulProxy</code>, 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 <code>DispatcherServlet</code> (to avoid multipart processing) in "/zuul/*".
|
||
In other words, if you have <code>zuul.routes.customers=/customers/**</code>, then you can <code>POST</code> large files to <code>/zuul/customers/*</code>.
|
||
The servlet path is externalized via <code>zuul.servletPath</code>.
|
||
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:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="title">application.yml</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-yaml hljs" data-lang="yaml">hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds: 60000
|
||
ribbon:
|
||
ConnectTimeout: 3000
|
||
ReadTimeout: 60000</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>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:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-bash hljs" data-lang="bash">$ curl -v -H "Transfer-Encoding: chunked" \
|
||
-F "file=@mylarge.iso" localhost:9999/zuul/simple/file</code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="query-string-encoding"><a class="anchor" href="#query-string-encoding"></a><a class="link" href="#query-string-encoding">9.9. Query String Encoding</a></h3>
|
||
<div class="paragraph">
|
||
<p>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’s <code>encodeURIComponent()</code> method.
|
||
While this causes no issues in most cases, some web servers can be picky with the encoding of complex query string.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>To force the original encoding of the query string, it is possible to pass a special flag to <code>ZuulProperties</code> so that the query string is taken as is with the <code>HttpServletRequest::getQueryString</code> method, as shown in the following example:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="title">application.yml</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-yaml hljs" data-lang="yaml"> zuul:
|
||
forceOriginalQueryStringEncoding: true</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="admonitionblock note">
|
||
<table>
|
||
<tr>
|
||
<td class="icon">
|
||
<i class="fa icon-note" title="Note"></i>
|
||
</td>
|
||
<td class="content">
|
||
This special flag works only with <code>SimpleHostRoutingFilter</code>. Also, you loose the ability to easily override
|
||
query parameters with <code>RequestContext.getCurrentContext().setRequestQueryParams(someOverriddenParameters)</code>, because
|
||
the query string is now fetched directly on the original <code>HttpServletRequest</code>.
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="request-uri-encoding"><a class="anchor" href="#request-uri-encoding"></a><a class="link" href="#request-uri-encoding">9.10. Request URI Encoding</a></h3>
|
||
<div class="paragraph">
|
||
<p>When processing the incoming request, request URI is decoded before matching them to routes.
|
||
The request URI is then re-encoded when the back end request is rebuilt in the route filters.
|
||
This can cause some unexpected behavior if your URI includes the encoded "/" character.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>To use the original request URI, it is possible to pass a special flag to 'ZuulProperties' so that the URI will be taken as is with the <code>HttpServletRequest::getRequestURI</code> method, as shown in the following example:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="title">application.yml</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-yaml hljs" data-lang="yaml"> zuul:
|
||
decodeUrl: false</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="admonitionblock note">
|
||
<table>
|
||
<tr>
|
||
<td class="icon">
|
||
<i class="fa icon-note" title="Note"></i>
|
||
</td>
|
||
<td class="content">
|
||
If you are overriding request URI using <code>requestURI</code> RequestContext attribute and this flag is set to false, then the URL set in the request context will not be encoded. It will be your responsibility to make sure the URL is already encoded.
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="plain-embedded-zuul"><a class="anchor" href="#plain-embedded-zuul"></a><a class="link" href="#plain-embedded-zuul">9.11. Plain Embedded Zuul</a></h3>
|
||
<div class="paragraph">
|
||
<p>If you use <code>@EnableZuulServer</code> (instead of <code>@EnableZuulProxy</code>), 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 <code>ZuulFilter</code> are installed automatically (as they are with <code>@EnableZuulProxy</code>) but without any of the proxy filters being added automatically.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>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:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="title">application.yml</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-yaml hljs" data-lang="yaml"> zuul:
|
||
routes:
|
||
api: /api/**</code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="disable-zuul-filters"><a class="anchor" href="#disable-zuul-filters"></a><a class="link" href="#disable-zuul-filters">9.12. Disable Zuul Filters</a></h3>
|
||
<div class="paragraph">
|
||
<p>Zuul for Spring Cloud comes with a number of <code>ZuulFilter</code> beans enabled by default in both proxy and server mode.
|
||
See <a 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</a> for the list of filters that you can enable.
|
||
If you want to disable one, set <code>zuul.<SimpleClassName>.<filterType>.disable=true</code>.
|
||
By convention, the package after <code>filters</code> is the Zuul filter type.
|
||
For example to disable <code>org.springframework.cloud.netflix.zuul.filters.post.SendResponseFilter</code>, set <code>zuul.SendResponseFilter.post.disable=true</code>.</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="hystrix-fallbacks-for-routes"><a class="anchor" href="#hystrix-fallbacks-for-routes"></a><a class="link" href="#hystrix-fallbacks-for-routes">9.13. Providing Hystrix Fallbacks For Routes</a></h3>
|
||
<div class="paragraph">
|
||
<p>When a circuit for a given route in Zuul is tripped, you can provide a fallback response by creating a bean of type <code>FallbackProvider</code>.
|
||
Within this bean, you need to specify the route ID the fallback is for and provide a <code>ClientHttpResponse</code> to return as a fallback.
|
||
The following example shows a relatively simple <code>FallbackProvider</code> implementation:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">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;
|
||
}
|
||
};
|
||
}
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The following example shows how the route configuration for the previous example might appear:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-yaml hljs" data-lang="yaml">zuul:
|
||
routes:
|
||
customers: /customers/**</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>If you would like to provide a default fallback for all routes, you can create a bean of type <code>FallbackProvider</code> and have the <code>getRoute</code> method return <code>*</code> or <code>null</code>, as shown in the following example:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">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;
|
||
}
|
||
};
|
||
}
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="zuul-timeouts"><a class="anchor" href="#zuul-timeouts"></a><a class="link" href="#zuul-timeouts">9.14. Zuul Timeouts</a></h3>
|
||
<div class="paragraph">
|
||
<p>If you want to configure the socket timeouts and read timeouts for requests proxied through Zuul, you have two options, based on your configuration:</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p>If Zuul uses service discovery, you need to configure these timeouts with the
|
||
<code>ribbon.ReadTimeout</code> and <code>ribbon.SocketTimeout</code> Ribbon properties.</p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>If you have configured Zuul routes by specifying URLs, you need to use
|
||
<code>zuul.host.connect-timeout-millis</code> and <code>zuul.host.socket-timeout-millis</code>.</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="zuul-redirect-location-rewrite"><a class="anchor" href="#zuul-redirect-location-rewrite"></a><a class="link" href="#zuul-redirect-location-rewrite">9.15. Rewriting the <code>Location</code> header</a></h3>
|
||
<div class="paragraph">
|
||
<p>If Zuul is fronting a web application, you may need to re-write the <code>Location</code> header when the web application redirects through a HTTP status code of <code>3XX</code>.
|
||
Otherwise, the browser redirects to the web application’s URL instead of the Zuul URL.
|
||
You can configure a <code>LocationRewriteFilter</code> Zuul filter to re-write the <code>Location</code> header to the Zuul’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:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">import org.springframework.cloud.netflix.zuul.filters.post.LocationRewriteFilter;
|
||
...
|
||
|
||
@Configuration
|
||
@EnableZuulProxy
|
||
public class ZuulConfig {
|
||
@Bean
|
||
public LocationRewriteFilter locationRewriteFilter() {
|
||
return new LocationRewriteFilter();
|
||
}
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="admonitionblock caution">
|
||
<table>
|
||
<tr>
|
||
<td class="icon">
|
||
<i class="fa icon-caution" title="Caution"></i>
|
||
</td>
|
||
<td class="content">
|
||
Use this filter carefully. The filter acts on the <code>Location</code> header of ALL <code>3XX</code> response codes, which may not be appropriate in all scenarios, such as when redirecting the user to an external URL.
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="enabling-cross-origin-requests"><a class="anchor" href="#enabling-cross-origin-requests"></a><a class="link" href="#enabling-cross-origin-requests">9.16. Enabling Cross Origin Requests</a></h3>
|
||
<div class="paragraph">
|
||
<p>By default Zuul routes all Cross Origin requests (CORS) to the services. If you want instead Zuul to handle these requests it can be done by providing custom <code>WebMvcConfigurer</code> bean:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@Bean
|
||
public WebMvcConfigurer corsConfigurer() {
|
||
return new WebMvcConfigurer() {
|
||
public void addCorsMappings(CorsRegistry registry) {
|
||
registry.addMapping("/path-1/**")
|
||
.allowedOrigins("https://allowed-origin.com")
|
||
.allowedMethods("GET", "POST");
|
||
}
|
||
};
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>In the example above, we allow <code>GET</code> and <code>POST</code> methods from <code><a href="https://allowed-origin.com" class="bare">allowed-origin.com</a></code> to send cross-origin requests to the endpoints starting with <code>path-1</code>.
|
||
You can apply CORS configuration to a specific path pattern or globally for the whole application, using <code>/**</code> mapping.
|
||
You can customize properties: <code>allowedOrigins</code>,<code>allowedMethods</code>,<code>allowedHeaders</code>,<code>exposedHeaders</code>,<code>allowCredentials</code> and <code>maxAge</code> via this configuration.</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="metrics"><a class="anchor" href="#metrics"></a><a class="link" href="#metrics">9.17. Metrics</a></h3>
|
||
<div class="paragraph">
|
||
<p>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 <code>/actuator/metrics</code>. The metrics will have a name that has the format
|
||
<code>ZUUL::EXCEPTION:errorCause:statusCode</code>.</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="zuul-developer-guide"><a class="anchor" href="#zuul-developer-guide"></a><a class="link" href="#zuul-developer-guide">9.18. Zuul Developer Guide</a></h3>
|
||
<div class="paragraph">
|
||
<p>For a general overview of how Zuul works, see <a href="https://github.com/Netflix/zuul/wiki/How-it-Works">the Zuul Wiki</a>.</p>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="the-zuul-servlet"><a class="anchor" href="#the-zuul-servlet"></a><a class="link" href="#the-zuul-servlet">9.18.1. The Zuul Servlet</a></h4>
|
||
<div class="paragraph">
|
||
<p>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 <code>/zuul</code>.
|
||
This path can be changed with the <code>zuul.servlet-path</code> property.</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="zuul-requestcontext"><a class="anchor" href="#zuul-requestcontext"></a><a class="link" href="#zuul-requestcontext">9.18.2. Zuul RequestContext</a></h4>
|
||
<div class="paragraph">
|
||
<p>To pass information between filters, Zuul uses a <a href="https://github.com/Netflix/zuul/blob/1.x/zuul-core/src/main/java/com/netflix/zuul/context/RequestContext.java"><code>RequestContext</code></a>.
|
||
Its data is held in a <code>ThreadLocal</code> specific to each request.
|
||
Information about where to route requests, errors, and the actual <code>HttpServletRequest</code> and <code>HttpServletResponse</code> are stored there.
|
||
The <code>RequestContext</code> extends <code>ConcurrentHashMap</code>, so anything can be stored in the context. <a href="https://github.com/spring-cloud/spring-cloud-netflix/blob/master/spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/support/FilterConstants.java"><code>FilterConstants</code></a> contains the keys used by the filters installed by Spring Cloud Netflix (more on these <a href="#zuul-developer-guide-enable-filters">later</a>).</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="enablezuulproxy-vs-enablezuulserver"><a class="anchor" href="#enablezuulproxy-vs-enablezuulserver"></a><a class="link" href="#enablezuulproxy-vs-enablezuulserver">9.18.3. <code>@EnableZuulProxy</code> vs. <code>@EnableZuulServer</code></a></h4>
|
||
<div class="paragraph">
|
||
<p>Spring Cloud Netflix installs a number of filters, depending on which annotation was used to enable Zuul. <code>@EnableZuulProxy</code> is a superset of <code>@EnableZuulServer</code>. In other words, <code>@EnableZuulProxy</code> contains all the filters installed by <code>@EnableZuulServer</code>. The additional filters in the “proxy” enable routing functionality. If you want a “blank” Zuul, you should use <code>@EnableZuulServer</code>.</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="zuul-developer-guide-enable-filters"><a class="anchor" href="#zuul-developer-guide-enable-filters"></a><a class="link" href="#zuul-developer-guide-enable-filters">9.18.4. <code>@EnableZuulServer</code> Filters</a></h4>
|
||
<div class="paragraph">
|
||
<p><code>@EnableZuulServer</code> creates a <code>SimpleRouteLocator</code> that loads route definitions from Spring Boot configuration files.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The following filters are installed (as normal Spring Beans):</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p>Pre filters:</p>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p><code>ServletDetectionFilter</code>: Detects whether the request is through the Spring Dispatcher. Sets a boolean with a key of <code>FilterConstants.IS_DISPATCHER_SERVLET_REQUEST_KEY</code>.</p>
|
||
</li>
|
||
<li>
|
||
<p><code>FormBodyWrapperFilter</code>: Parses form data and re-encodes it for downstream requests.</p>
|
||
</li>
|
||
<li>
|
||
<p><code>DebugFilter</code>: If the <code>debug</code> request parameter is set, sets <code>RequestContext.setDebugRouting()</code> and <code>RequestContext.setDebugRequest()</code> to <code>true</code>.</p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
</li>
|
||
<li>
|
||
<p>Route filters:</p>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p><code>SendForwardFilter</code>: Forwards requests by using the Servlet <code>RequestDispatcher</code>. The forwarding location is stored in the <code>RequestContext</code> attribute, <code>FilterConstants.FORWARD_TO_KEY</code>. This is useful for forwarding to endpoints in the current application.</p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
</li>
|
||
<li>
|
||
<p>Post filters:</p>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p><code>SendResponseFilter</code>: Writes responses from proxied requests to the current response.</p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
</li>
|
||
<li>
|
||
<p>Error filters:</p>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p><code>SendErrorFilter</code>: Forwards to <code>/error</code> (by default) if <code>RequestContext.getThrowable()</code> is not null. You can change the default forwarding path (<code>/error</code>) by setting the <code>error.path</code> property.</p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="enablezuulproxy-filters"><a class="anchor" href="#enablezuulproxy-filters"></a><a class="link" href="#enablezuulproxy-filters">9.18.5. <code>@EnableZuulProxy</code> Filters</a></h4>
|
||
<div class="paragraph">
|
||
<p>Creates a <code>DiscoveryClientRouteLocator</code> that loads route definitions from a <code>DiscoveryClient</code> (such as Eureka) as well as from properties. A route is created for each <code>serviceId</code> from the <code>DiscoveryClient</code>. As new services are added, the routes are refreshed.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>In addition to the filters described earlier, the following filters are installed (as normal Spring Beans):</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p>Pre filters:</p>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p><code>PreDecorationFilter</code>: Determines where and how to route, depending on the supplied <code>RouteLocator</code>. It also sets various proxy-related headers for downstream requests.</p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
</li>
|
||
<li>
|
||
<p>Route filters:</p>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p><code>RibbonRoutingFilter</code>: Uses Ribbon, Hystrix, and pluggable HTTP clients to send requests. Service IDs are found in the <code>RequestContext</code> attribute, <code>FilterConstants.SERVICE_ID_KEY</code>. This filter can use different HTTP clients:</p>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p>Apache <code>HttpClient</code>: The default client.</p>
|
||
</li>
|
||
<li>
|
||
<p>Squareup <code>OkHttpClient</code> v3: Enabled by having the <code>com.squareup.okhttp3:okhttp</code> library on the classpath and setting <code>ribbon.okhttp.enabled=true</code>.</p>
|
||
</li>
|
||
<li>
|
||
<p>Netflix Ribbon HTTP client: Enabled by setting <code>ribbon.restclient.enabled=true</code>. This client has limitations, including that it does not support the PATCH method, but it also has built-in retry.</p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
</li>
|
||
<li>
|
||
<p><code>SimpleHostRoutingFilter</code>: Sends requests to predetermined URLs through an Apache HttpClient. URLs are found in <code>RequestContext.getRouteHost()</code>.</p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="custom-zuul-filter-examples"><a class="anchor" href="#custom-zuul-filter-examples"></a><a class="link" href="#custom-zuul-filter-examples">9.18.6. Custom Zuul Filter Examples</a></h4>
|
||
<div class="paragraph">
|
||
<p>Most of the following "How to Write" examples below are included <a href="https://github.com/spring-cloud-samples/sample-zuul-filters">Sample Zuul Filters</a> project. There are also examples of manipulating the request or response body in that repository.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>This section includes the following examples:</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p><a href="#zuul-developer-guide-sample-pre-filter">How to Write a Pre Filter</a></p>
|
||
</li>
|
||
<li>
|
||
<p><a href="#zuul-developer-guide-sample-route-filter">How to Write a Route Filter</a></p>
|
||
</li>
|
||
<li>
|
||
<p><a href="#zuul-developer-guide-sample-post-filter">How to Write a Post Filter</a></p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
<div class="sect4">
|
||
<h5 id="zuul-developer-guide-sample-pre-filter"><a class="anchor" href="#zuul-developer-guide-sample-pre-filter"></a><a class="link" href="#zuul-developer-guide-sample-pre-filter">How to Write a Pre Filter</a></h5>
|
||
<div class="paragraph">
|
||
<p>Pre filters set up data in the <code>RequestContext</code> 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:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">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
|
||
&& !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;
|
||
}
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The preceding filter populates <code>SERVICE_ID_KEY</code> from the <code>sample</code> 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 <code>sample</code> instead.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Now that <code>SERVICE_ID_KEY</code> is populated, <code>PreDecorationFilter</code> does not run and <code>RibbonRoutingFilter</code> runs.</p>
|
||
</div>
|
||
<div class="admonitionblock tip">
|
||
<table>
|
||
<tr>
|
||
<td class="icon">
|
||
<i class="fa icon-tip" title="Tip"></i>
|
||
</td>
|
||
<td class="content">
|
||
If you want to route to a full URL, call <code>ctx.setRouteHost(url)</code> instead.
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>To modify the path to which routing filters forward, set the <code>REQUEST_URI_KEY</code>.</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect4">
|
||
<h5 id="zuul-developer-guide-sample-route-filter"><a class="anchor" href="#zuul-developer-guide-sample-route-filter"></a><a class="link" href="#zuul-developer-guide-sample-route-filter">How to Write a Route Filter</a></h5>
|
||
<div class="paragraph">
|
||
<p>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:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">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
|
||
&& 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<String> headerNames = request.getHeaderNames();
|
||
while (headerNames.hasMoreElements()) {
|
||
String name = headerNames.nextElement();
|
||
Enumeration<String> 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 && 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<String, String> responseHeaders = new LinkedMultiValueMap<>();
|
||
|
||
for (Map.Entry<String, List<String>> 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;
|
||
}
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The preceding filter translates Servlet request information into OkHttp3 request information, executes an HTTP request, and translates OkHttp3 response information to the Servlet response.</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect4">
|
||
<h5 id="zuul-developer-guide-sample-post-filter"><a class="anchor" href="#zuul-developer-guide-sample-post-filter"></a><a class="link" href="#zuul-developer-guide-sample-post-filter">How to Write a Post Filter</a></h5>
|
||
<div class="paragraph">
|
||
<p>Post filters typically manipulate the response. The following filter adds a random <code>UUID</code> as the <code>X-Sample</code> header:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">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;
|
||
}
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="admonitionblock note">
|
||
<table>
|
||
<tr>
|
||
<td class="icon">
|
||
<i class="fa icon-note" title="Note"></i>
|
||
</td>
|
||
<td class="content">
|
||
Other manipulations, such as transforming the response body, are much more complex and computationally intensive.
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="how-zuul-errors-work"><a class="anchor" href="#how-zuul-errors-work"></a><a class="link" href="#how-zuul-errors-work">9.18.7. How Zuul Errors Work</a></h4>
|
||
<div class="paragraph">
|
||
<p>If an exception is thrown during any portion of the Zuul filter lifecycle, the error filters are executed.
|
||
The <code>SendErrorFilter</code> is only run if <code>RequestContext.getThrowable()</code> is not <code>null</code>.
|
||
It then sets specific <code>javax.servlet.error.*</code> attributes in the request and forwards the request to the Spring Boot error page.</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="zuul-eager-application-context-loading"><a class="anchor" href="#zuul-eager-application-context-loading"></a><a class="link" href="#zuul-eager-application-context-loading">9.18.8. Zuul Eager Application Context Loading</a></h4>
|
||
<div class="paragraph">
|
||
<p>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:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="title">application.yml</div>
|
||
<div class="content">
|
||
<pre>zuul:
|
||
ribbon:
|
||
eager-load:
|
||
enabled: true</pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect1">
|
||
<h2 id="polyglot-support-with-sidecar"><a class="anchor" href="#polyglot-support-with-sidecar"></a><a class="link" href="#polyglot-support-with-sidecar">10. Polyglot support with Sidecar</a></h2>
|
||
<div class="sectionbody">
|
||
<div class="paragraph">
|
||
<p>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 <a href="https://github.com/Netflix/Prana">Netflix Prana</a>.
|
||
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.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>To include Sidecar in your project, use the dependency with a group ID of <code>org.springframework.cloud</code>
|
||
and artifact ID or <code>spring-cloud-netflix-sidecar</code>.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>To enable the Sidecar, create a Spring Boot application with <code>@EnableSidecar</code>.
|
||
This annotation includes <code>@EnableCircuitBreaker</code>, <code>@EnableDiscoveryClient</code>, and <code>@EnableZuulProxy</code>.
|
||
Run the resulting application on the same host as the non-JVM application.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>To configure the side car, add <code>sidecar.port</code> and <code>sidecar.health-uri</code> to <code>application.yml</code>.
|
||
The <code>sidecar.port</code> property is the port on which the non-JVM application listens.
|
||
This is so the Sidecar can properly register the application with Eureka.
|
||
The <code>sidecar.secure-port-enabled</code> options provides a way to enable secure port for traffic.
|
||
The <code>sidecar.health-uri</code> 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:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="title">health-uri-document</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-json hljs" data-lang="json">{
|
||
"status":"UP"
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The following application.yml example shows sample configuration for a Sidecar application:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="title">application.yml</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-yaml hljs" data-lang="yaml">server:
|
||
port: 5678
|
||
spring:
|
||
application:
|
||
name: sidecar
|
||
|
||
sidecar:
|
||
port: 8000
|
||
health-uri: http://localhost:8000/health.json</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The API for the <code>DiscoveryClient.getInstances()</code> method is <code>/hosts/{serviceId}</code>.
|
||
The following example response for <code>/hosts/customers</code> returns two instances on different hosts:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="title">/hosts/customers</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-json hljs" data-lang="json">[
|
||
{
|
||
"host": "myhost",
|
||
"port": 9000,
|
||
"uri": "https://myhost:9000",
|
||
"serviceId": "CUSTOMERS",
|
||
"secure": false
|
||
},
|
||
{
|
||
"host": "myhost2",
|
||
"port": 9000,
|
||
"uri": "https://myhost2:9000",
|
||
"serviceId": "CUSTOMERS",
|
||
"secure": false
|
||
}
|
||
]</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>This API is accessible to the non-JVM application (if the sidecar is on port 5678) at <code><a href="http://localhost:5678/hosts/{serviceId}" class="bare">localhost:5678/hosts/{serviceId}</a></code>.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The Zuul proxy automatically adds routes for each service known in Eureka to <code>/<serviceId></code>, so the customers service is available at <code>/customers</code>.
|
||
The non-JVM application can access the customer service at <code><a href="http://localhost:5678/customers" class="bare">localhost:5678/customers</a></code> (assuming the sidecar is listening on port 5678).</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>If the Config Server is registered with Eureka, the non-JVM application can access it through the Zuul proxy.
|
||
If the <code>serviceId</code> of the ConfigServer is <code>configserver</code> and the Sidecar is on port 5678, then it can be accessed at <a href="http://localhost:5678/configserver" class="bare">localhost:5678/configserver</a>.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Non-JVM applications can take advantage of the Config Server’s ability to return YAML documents.
|
||
For example, a call to <a href="https://sidecar.local.spring.io:5678/configserver/default-master.yml" class="bare">sidecar.local.spring.io:5678/configserver/default-master.yml</a>
|
||
might result in a YAML document resembling the following:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-yaml hljs" data-lang="yaml">eureka:
|
||
client:
|
||
serviceUrl:
|
||
defaultZone: http://localhost:8761/eureka/
|
||
password: password
|
||
info:
|
||
description: Spring Cloud Samples
|
||
url: https://github.com/spring-cloud-samples</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>To enable the health check request to accept all certificates when using HTTPs set <code>sidecar.accept-all-ssl-certificates</code> to `true.</p>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect1">
|
||
<h2 id="retrying-failed-requests"><a class="anchor" href="#retrying-failed-requests"></a><a class="link" href="#retrying-failed-requests">11. Retrying Failed Requests</a></h2>
|
||
<div class="sectionbody">
|
||
<div class="paragraph">
|
||
<p>Spring Cloud Netflix offers a variety of ways to make HTTP requests.
|
||
You can use a load balanced <code>RestTemplate</code>, 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 <a href="https://github.com/spring-projects/spring-retry">Spring Retry</a> on your application’s classpath.
|
||
When Spring Retry is present, load-balanced <code>RestTemplates</code>, Feign, and Zuul automatically retry any failed requests (assuming your configuration allows doing so).</p>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="backoff-policies"><a class="anchor" href="#backoff-policies"></a><a class="link" href="#backoff-policies">11.1. BackOff Policies</a></h3>
|
||
<div class="paragraph">
|
||
<p>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 <code>LoadBalancedRetryFactory</code> and override the <code>createBackOffPolicy</code> method for a given service, as shown in the following example:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@Configuration
|
||
public class MyConfiguration {
|
||
@Bean
|
||
LoadBalancedRetryFactory retryFactory() {
|
||
return new LoadBalancedRetryFactory() {
|
||
@Override
|
||
public BackOffPolicy createBackOffPolicy(String service) {
|
||
return new ExponentialBackOffPolicy();
|
||
}
|
||
};
|
||
}
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="configuration"><a class="anchor" href="#configuration"></a><a class="link" href="#configuration">11.2. Configuration</a></h3>
|
||
<div class="paragraph">
|
||
<p>When you use Ribbon with Spring Retry, you can control the retry functionality by configuring certain Ribbon properties.
|
||
To do so, set the <code>client.ribbon.MaxAutoRetries</code>, <code>client.ribbon.MaxAutoRetriesNextServer</code>, and <code>client.ribbon.OkToRetryOnAllOperations</code> properties.
|
||
See the <a href="https://github.com/Netflix/ribbon/wiki/Getting-Started#the-properties-file-sample-clientproperties">Ribbon documentation</a> for a description of what these properties do.</p>
|
||
</div>
|
||
<div class="admonitionblock warning">
|
||
<table>
|
||
<tr>
|
||
<td class="icon">
|
||
<i class="fa icon-warning" title="Warning"></i>
|
||
</td>
|
||
<td class="content">
|
||
Enabling <code>client.ribbon.OkToRetryOnAllOperations</code> includes retrying POST requests, which can have an impact
|
||
on the server’s resources, due to the buffering of the request body.
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
<div class="admonitionblock caution">
|
||
<table>
|
||
<tr>
|
||
<td class="icon">
|
||
<i class="fa icon-caution" title="Caution"></i>
|
||
</td>
|
||
<td class="content">
|
||
The property names are case-sensitive, and since some of these properties are defined in the Netflix Ribbon project, they are in Pascal Case and the ones from Spring Cloud are in Camel Case.
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>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 <code>clientName.ribbon.retryableStatusCodes</code> property, as shown in the following example:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-yaml hljs" data-lang="yaml">clientName:
|
||
ribbon:
|
||
retryableStatusCodes: 404,502</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>You can also create a bean of type <code>LoadBalancedRetryPolicy</code> and implement the <code>retryableStatusCode</code> method to retry a request given the status code.</p>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="zuul"><a class="anchor" href="#zuul"></a><a class="link" href="#zuul">11.2.1. Zuul</a></h4>
|
||
<div class="paragraph">
|
||
<p>You can turn off Zuul’s retry functionality by setting <code>zuul.retryable</code> to <code>false</code>.
|
||
You can also disable retry functionality on a route-by-route basis by setting <code>zuul.routes.routename.retryable</code> to <code>false</code>.</p>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect1">
|
||
<h2 id="http-clients"><a class="anchor" href="#http-clients"></a><a class="link" href="#http-clients">12. HTTP Clients</a></h2>
|
||
<div class="sectionbody">
|
||
<div class="paragraph">
|
||
<p>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 <code>ClosableHttpClient</code> if you
|
||
are using the Apache Http Cient or <code>OkHttpClient</code> if you are using OK HTTP.</p>
|
||
</div>
|
||
<div class="admonitionblock note">
|
||
<table>
|
||
<tr>
|
||
<td class="icon">
|
||
<i class="fa icon-note" title="Note"></i>
|
||
</td>
|
||
<td class="content">
|
||
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.
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect1">
|
||
<h2 id="modules-in-maintenance-mode"><a class="anchor" href="#modules-in-maintenance-mode"></a><a class="link" href="#modules-in-maintenance-mode">13. Modules In Maintenance Mode</a></h2>
|
||
<div class="sectionbody">
|
||
<div class="paragraph">
|
||
<p>Placing a module in maintenance mode means that the Spring Cloud team will no longer be adding new features to the module.
|
||
We will fix blocker bugs and security issues, and we will also consider and review small pull requests from the community.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>We intend to continue to support these modules for a period of at least a year from the general availability
|
||
of the Greenwich release train.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The following Spring Cloud Netflix modules and corresponding starters will be placed into maintenance mode:</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p>spring-cloud-netflix-archaius</p>
|
||
</li>
|
||
<li>
|
||
<p>spring-cloud-netflix-hystrix-contract</p>
|
||
</li>
|
||
<li>
|
||
<p>spring-cloud-netflix-hystrix-dashboard</p>
|
||
</li>
|
||
<li>
|
||
<p>spring-cloud-netflix-hystrix-stream</p>
|
||
</li>
|
||
<li>
|
||
<p>spring-cloud-netflix-hystrix</p>
|
||
</li>
|
||
<li>
|
||
<p>spring-cloud-netflix-ribbon</p>
|
||
</li>
|
||
<li>
|
||
<p>spring-cloud-netflix-turbine-stream</p>
|
||
</li>
|
||
<li>
|
||
<p>spring-cloud-netflix-turbine</p>
|
||
</li>
|
||
<li>
|
||
<p>spring-cloud-netflix-zuul</p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
<div class="admonitionblock note">
|
||
<table>
|
||
<tr>
|
||
<td class="icon">
|
||
<i class="fa icon-note" title="Note"></i>
|
||
</td>
|
||
<td class="content">
|
||
This does not include the Eureka or concurrency-limits modules.
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect1">
|
||
<h2 id="configuration-properties"><a class="anchor" href="#configuration-properties"></a><a class="link" href="#configuration-properties">14. Configuration properties</a></h2>
|
||
<div class="sectionbody">
|
||
<div class="paragraph">
|
||
<p>To see the list of all Spring Cloud Netflix related configuration properties please check <a href="appendix.html">the Appendix page</a>.</p>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<script type="text/javascript" src="js/tocbot/tocbot.min.js"></script>
|
||
<script type="text/javascript" src="js/toc.js"></script>
|
||
<link rel="stylesheet" href="js/highlight/styles/atom-one-dark-reasonable.min.css">
|
||
<script src="js/highlight/highlight.min.js"></script>
|
||
<script>hljs.initHighlighting()</script>
|
||
</body>
|
||
</html> |