You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
495 lines
31 KiB
495 lines
31 KiB
<?xml version="1.0" encoding="UTF-8"?> |
|
<?asciidoc-toc?> |
|
<?asciidoc-numbered?> |
|
<book xmlns="http://docbook.org/ns/docbook" xmlns:xl="http://www.w3.org/1999/xlink" version="5.0" xml:lang="en"> |
|
<info> |
|
<title>Cloud Native Applications</title> |
|
<date>2017-11-03</date> |
|
</info> |
|
<preface> |
|
<title></title> |
|
<simpara><link xl:href="http://pivotal.io/platform-as-a-service/migrating-to-cloud-native-application-architectures-ebook">Cloud Native</link> is a style of application development that encourages easy adoption of best practices in the areas of continuous delivery and value-driven development. A related discipline is that of building <link xl:href="http://12factor.net/">12-factor Apps</link> in which development practices are aligned with delivery and operations goals, for instance by using declarative programming and management and monitoring. Spring Cloud facilitates these styles of development in a number of specific ways and the starting point is a set of features that all components in a distributed system either need or need easy access to when required.</simpara> |
|
<simpara>Many of those features are covered by <link xl:href="http://projects.spring.io/spring-boot">Spring Boot</link>, which we build on in Spring Cloud. Some more are delivered by Spring Cloud as two libraries: Spring Cloud Context and Spring Cloud Commons. Spring Cloud Context provides utilities and special services for the <literal>ApplicationContext</literal> of a Spring Cloud application (bootstrap context, encryption, refresh scope and environment endpoints). Spring Cloud Commons is a set of abstractions and common classes used in different Spring Cloud implementations (eg. Spring Cloud Netflix vs. Spring Cloud Consul).</simpara> |
|
<simpara>If you are getting an exception due to "Illegal key size" and you are using Sun’s JDK, you need to install the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files. See the following links for more information:</simpara> |
|
<itemizedlist> |
|
<listitem> |
|
<simpara><link xl:href="http://www.oracle.com/technetwork/java/javase/downloads/jce-6-download-429243.html">Java 6 JCE</link></simpara> |
|
</listitem> |
|
<listitem> |
|
<simpara><link xl:href="http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html">Java 7 JCE</link></simpara> |
|
</listitem> |
|
<listitem> |
|
<simpara><link xl:href="http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html">Java 8 JCE</link></simpara> |
|
</listitem> |
|
</itemizedlist> |
|
<simpara>Extract files into JDK/jre/lib/security folder (whichever version of JRE/JDK x64/x86 you are using).</simpara> |
|
<note> |
|
<simpara>Spring Cloud is released under the non-restrictive Apache 2.0 license. If you would like to contribute to this section of the documentation or if you find an error, please find the source code and issue trackers in the project at <link xl:href="https://github.com/spring-cloud/spring-cloud-commons/tree/master/docs/src/main/asciidoc">github</link>.</simpara> |
|
</note> |
|
</preface> |
|
<chapter xml:id="_spring_cloud_context_application_context_services"> |
|
<title>Spring Cloud Context: Application Context Services</title> |
|
<simpara>Spring Boot has an opinionated view of how to build an application |
|
with Spring: for instance it has conventional locations for common |
|
configuration file, and endpoints for common management and monitoring |
|
tasks. Spring Cloud builds on top of that and adds a few features that |
|
probably all components in a system would use or occasionally need.</simpara> |
|
<section xml:id="_the_bootstrap_application_context"> |
|
<title>The Bootstrap Application Context</title> |
|
<simpara>A Spring Cloud application operates by creating a "bootstrap" |
|
context, which is a parent context for the main application. Out of |
|
the box it is responsible for loading configuration properties from |
|
the external sources, and also decrypting properties in the local |
|
external configuration files. The two contexts share an <literal>Environment</literal> |
|
which is the source of external properties for any Spring |
|
application. Bootstrap properties are added with high precedence, so |
|
they cannot be overridden by local configuration, by default.</simpara> |
|
<simpara>The bootstrap context uses a different convention for locating |
|
external configuration than the main application context, so instead |
|
of <literal>application.yml</literal> (or <literal>.properties</literal>) you use <literal>bootstrap.yml</literal>, |
|
keeping the external configuration for bootstrap and main context |
|
nicely separate. Example:</simpara> |
|
<formalpara> |
|
<title>bootstrap.yml</title> |
|
<para> |
|
<screen>spring: |
|
application: |
|
name: foo |
|
cloud: |
|
config: |
|
uri: ${SPRING_CONFIG_URI:http://localhost:8888}</screen> |
|
</para> |
|
</formalpara> |
|
<simpara>It is a good idea to set the <literal>spring.application.name</literal> (in |
|
<literal>bootstrap.yml</literal> or <literal>application.yml</literal>) if your application needs any |
|
application-specific configuration from the server.</simpara> |
|
<simpara>You can disable the bootstrap process completely by setting |
|
<literal>spring.cloud.bootstrap.enabled=false</literal> (e.g. in System properties).</simpara> |
|
</section> |
|
<section xml:id="_application_context_hierarchies"> |
|
<title>Application Context Hierarchies</title> |
|
<simpara>If you build an application context from <literal>SpringApplication</literal> or |
|
<literal>SpringApplicationBuilder</literal>, then the Bootstrap context is added as a |
|
parent to that context. It is a feature of Spring that child contexts |
|
inherit property sources and profiles from their parent, so the "main" |
|
application context will contain additional property sources, compared |
|
to building the same context without Spring Cloud Config. The |
|
additional property sources are:</simpara> |
|
<itemizedlist> |
|
<listitem> |
|
<simpara>"bootstrap": an optional <literal>CompositePropertySource</literal> appears with high |
|
priority if any <literal>PropertySourceLocators</literal> are found in the Bootstrap |
|
context, and they have non-empty properties. An example would be |
|
properties from the Spring Cloud Config Server. See |
|
<link xl:href="#customizing-bootstrap-property-sources">below</link> for instructions |
|
on how to customize the contents of this property source.</simpara> |
|
</listitem> |
|
<listitem> |
|
<simpara>"applicationConfig: [classpath:bootstrap.yml]" (and friends if |
|
Spring profiles are active). If you have a <literal>bootstrap.yml</literal> (or |
|
properties) then those properties are used to configure the Bootstrap |
|
context, and then they get added to the child context when its parent |
|
is set. They have lower precedence than the <literal>application.yml</literal> (or |
|
properties) and any other property sources that are added to the child |
|
as a normal part of the process of creating a Spring Boot |
|
application. See <link xl:href="#customizing-bootstrap-properties">below</link> for |
|
instructions on how to customize the contents of these property |
|
sources.</simpara> |
|
</listitem> |
|
</itemizedlist> |
|
<simpara>Because of the ordering rules of property sources the "bootstrap" |
|
entries take precedence, but note that these do not contain any data |
|
from <literal>bootstrap.yml</literal>, which has very low precedence, but can be used |
|
to set defaults.</simpara> |
|
<simpara>You can extend the context hierarchy by simply setting the parent |
|
context of any <literal>ApplicationContext</literal> you create, e.g. using its own |
|
interface, or with the <literal>SpringApplicationBuilder</literal> convenience methods |
|
(<literal>parent()</literal>, <literal>child()</literal> and <literal>sibling()</literal>). The bootstrap context will be |
|
the parent of the most senior ancestor that you create yourself. |
|
Every context in the hierarchy will have its own "bootstrap" property |
|
source (possibly empty) to avoid promoting values inadvertently from |
|
parents down to their descendants. Every context in the hierarchy can |
|
also (in principle) have a different <literal>spring.application.name</literal> and |
|
hence a different remote property source if there is a Config |
|
Server. Normal Spring application context behaviour rules apply to |
|
property resolution: properties from a child context override those in |
|
the parent, by name and also by property source name (if the child has |
|
a property source with the same name as the parent, the one from the |
|
parent is not included in the child).</simpara> |
|
<simpara>Note that the <literal>SpringApplicationBuilder</literal> allows you to share an |
|
<literal>Environment</literal> amongst the whole hierarchy, but that is not the |
|
default. Thus, sibling contexts in particular do not need to have the |
|
same profiles or property sources, even though they will share common |
|
things with their parent.</simpara> |
|
</section> |
|
<section xml:id="customizing-bootstrap-properties"> |
|
<title>Changing the Location of Bootstrap Properties</title> |
|
<simpara>The <literal>bootstrap.yml</literal> (or <literal>.properties</literal>) location can be specified using |
|
<literal>spring.cloud.bootstrap.name</literal> (default "bootstrap") or |
|
<literal>spring.cloud.bootstrap.location</literal> (default empty), e.g. in System |
|
properties. Those properties behave like the <literal>spring.config.*</literal> |
|
variants with the same name, in fact they are used to set up the |
|
bootstrap <literal>ApplicationContext</literal> by setting those properties in its |
|
<literal>Environment</literal>. If there is an active profile (from |
|
<literal>spring.profiles.active</literal> or through the <literal>Environment</literal> API in the |
|
context you are building) then properties in that profile will be |
|
loaded as well, just like in a regular Spring Boot app, e.g. from |
|
<literal>bootstrap-development.properties</literal> for a "development" profile.</simpara> |
|
</section> |
|
<section xml:id="overriding-bootstrap-properties"> |
|
<title>Overriding the Values of Remote Properties</title> |
|
<simpara>The property sources that are added to you application by the |
|
bootstrap context are often "remote" (e.g. from a Config Server), and |
|
by default they cannot be overridden locally, except on the command |
|
line. If you want to allow your applications to override the remote |
|
properties with their own System properties or config files, the |
|
remote property source has to grant it permission by setting |
|
<literal>spring.cloud.config.allowOverride=true</literal> (it doesn’t work to set this |
|
locally). Once that flag is set there are some finer grained settings |
|
to control the location of the remote properties in relation to System |
|
properties and the application’s local configuration: |
|
<literal>spring.cloud.config.overrideNone=true</literal> to override with any local |
|
property source, and |
|
<literal>spring.cloud.config.overrideSystemProperties=false</literal> if only System |
|
properties and env vars should override the remote settings, but not |
|
the local config files.</simpara> |
|
</section> |
|
<section xml:id="_customizing_the_bootstrap_configuration"> |
|
<title>Customizing the Bootstrap Configuration</title> |
|
<simpara>The bootstrap context can be trained to do anything you like by adding |
|
entries to <literal>/META-INF/spring.factories</literal> under the key |
|
<literal>org.springframework.cloud.bootstrap.BootstrapConfiguration</literal>. This is |
|
a comma-separated list of Spring <literal>@Configuration</literal> classes which will |
|
be used to create the context. Any beans that you want to be available |
|
to the main application context for autowiring can be created here, |
|
and also there is a special contract for <literal>@Beans</literal> of type |
|
<literal>ApplicationContextInitializer</literal>. Classes can be marked with an <literal>@Order</literal> |
|
if you want to control the startup sequence (the default order is |
|
"last").</simpara> |
|
<warning> |
|
<simpara>Be careful when adding custom <literal>BootstrapConfiguration</literal> that the |
|
classes you add are not <literal>@ComponentScanned</literal> by mistake into your |
|
"main" application context, where they might not be needed. |
|
Use a separate package name for boot configuration classes that is |
|
not already covered by your <literal>@ComponentScan</literal> or <literal>@SpringBootApplication</literal> |
|
annotated configuration classes.</simpara> |
|
</warning> |
|
<simpara>The bootstrap process ends by injecting initializers into the main |
|
<literal>SpringApplication</literal> instance (i.e. the normal Spring Boot startup |
|
sequence, whether it is running as a standalone app or deployed in an |
|
application server). First a bootstrap context is created from the |
|
classes found in <literal>spring.factories</literal> and then all <literal>@Beans</literal> of type |
|
<literal>ApplicationContextInitializer</literal> are added to the main |
|
<literal>SpringApplication</literal> before it is started.</simpara> |
|
</section> |
|
<section xml:id="customizing-bootstrap-property-sources"> |
|
<title>Customizing the Bootstrap Property Sources</title> |
|
<simpara>The default property source for external configuration added by the |
|
bootstrap process is the Config Server, but you can add additional |
|
sources by adding beans of type <literal>PropertySourceLocator</literal> to the |
|
bootstrap context (via <literal>spring.factories</literal>). You could use this to |
|
insert additional properties from a different server, or from a |
|
database, for instance.</simpara> |
|
<simpara>As an example, consider the following trivial custom locator:</simpara> |
|
<programlisting language="java" linenumbering="unnumbered">@Configuration |
|
public class CustomPropertySourceLocator implements PropertySourceLocator { |
|
|
|
@Override |
|
public PropertySource<?> locate(Environment environment) { |
|
return new MapPropertySource("customProperty", |
|
Collections.<String, Object>singletonMap("property.from.sample.custom.source", "worked as intended")); |
|
} |
|
|
|
}</programlisting> |
|
<simpara>The <literal>Environment</literal> that is passed in is the one for the |
|
<literal>ApplicationContext</literal> about to be created, i.e. the one that we are |
|
supplying additional property sources for. It will already have its |
|
normal Spring Boot-provided property sources, so you can use those to |
|
locate a property source specific to this <literal>Environment</literal> (e.g. by |
|
keying it on the <literal>spring.application.name</literal>, as is done in the default |
|
Config Server property source locator).</simpara> |
|
<simpara>If you create a jar with this class in it and then add a |
|
<literal>META-INF/spring.factories</literal> containing:</simpara> |
|
<screen>org.springframework.cloud.bootstrap.BootstrapConfiguration=sample.custom.CustomPropertySourceLocator</screen> |
|
<simpara>then the "customProperty" <literal>PropertySource</literal> will show up in any |
|
application that includes that jar on its classpath.</simpara> |
|
</section> |
|
<section xml:id="_environment_changes"> |
|
<title>Environment Changes</title> |
|
<simpara>The application will listen for an <literal>EnvironmentChangeEvent</literal> and react |
|
to the change in a couple of standard ways (additional |
|
<literal>ApplicationListeners</literal> can be added as <literal>@Beans</literal> by the user in the |
|
normal way). When an <literal>EnvironmentChangeEvent</literal> is observed it will |
|
have a list of key values that have changed, and the application will |
|
use those to:</simpara> |
|
<itemizedlist> |
|
<listitem> |
|
<simpara>Re-bind any <literal>@ConfigurationProperties</literal> beans in the context</simpara> |
|
</listitem> |
|
<listitem> |
|
<simpara>Set the logger levels for any properties in <literal>logging.level.*</literal></simpara> |
|
</listitem> |
|
</itemizedlist> |
|
<simpara>Note that the Config Client does not by default poll for changes in |
|
the <literal>Environment</literal>, and generally we would not recommend that approach |
|
for detecting changes (although you could set it up with a |
|
<literal>@Scheduled</literal> annotation). If you have a scaled-out client application |
|
then it is better to broadcast the <literal>EnvironmentChangeEvent</literal> to all |
|
the instances instead of having them polling for changes (e.g. using |
|
the <link xl:href="https://github.com/spring-cloud/spring-cloud-bus">Spring Cloud |
|
Bus</link>).</simpara> |
|
<simpara>The <literal>EnvironmentChangeEvent</literal> covers a large class of refresh use |
|
cases, as long as you can actually make a change to the <literal>Environment</literal> |
|
and publish the event (those APIs are public and part of core |
|
Spring). You can verify the changes are bound to |
|
<literal>@ConfigurationProperties</literal> beans by visiting the <literal>/configprops</literal> |
|
endpoint (normal Spring Boot Actuator feature). For instance a |
|
<literal>DataSource</literal> can have its <literal>maxPoolSize</literal> changed at runtime (the |
|
default <literal>DataSource</literal> created by Spring Boot is an |
|
<literal>@ConfigurationProperties</literal> bean) and grow capacity |
|
dynamically. Re-binding <literal>@ConfigurationProperties</literal> does not cover |
|
another large class of use cases, where you need more control over the |
|
refresh, and where you need a change to be atomic over the whole |
|
<literal>ApplicationContext</literal>. To address those concerns we have |
|
<literal>@RefreshScope</literal>.</simpara> |
|
</section> |
|
<section xml:id="_refresh_scope"> |
|
<title>Refresh Scope</title> |
|
<simpara>A Spring <literal>@Bean</literal> that is marked as <literal>@RefreshScope</literal> will get special |
|
treatment when there is a configuration change. This addresses the |
|
problem of stateful beans that only get their configuration injected |
|
when they are initialized. For instance if a <literal>DataSource</literal> has open |
|
connections when the database URL is changed via the <literal>Environment</literal>, we |
|
probably want the holders of those connections to be able to complete |
|
what they are doing. Then the next time someone borrows a connection |
|
from the pool he gets one with the new URL.</simpara> |
|
<simpara>Refresh scope beans are lazy proxies that initialize when they are |
|
used (i.e. when a method is called), and the scope acts as a cache of |
|
initialized values. To force a bean to re-initialize on the next |
|
method call you just need to invalidate its cache entry.</simpara> |
|
<simpara>The <literal>RefreshScope</literal> is a bean in the context and it has a public method |
|
<literal>refreshAll()</literal> to refresh all beans in the scope by clearing the |
|
target cache. There is also a <literal>refresh(String)</literal> method to refresh an |
|
individual bean by name. This functionality is exposed in the |
|
<literal>/refresh</literal> endpoint (over HTTP or JMX).</simpara> |
|
<note> |
|
<simpara><literal>@RefreshScope</literal> works (technically) on an <literal>@Configuration</literal> |
|
class, but it might lead to surprising behaviour: e.g. it does <emphasis role="strong">not</emphasis> |
|
mean that all the <literal>@Beans</literal> defined in that class are themselves |
|
<literal>@RefreshScope</literal>. Specifically, anything that depends on those beans |
|
cannot rely on them being updated when a refresh is initiated, unless |
|
it is itself in <literal>@RefreshScope</literal> (in which it will be rebuilt on a |
|
refresh and its dependencies re-injected, at which point they will be |
|
re-initialized from the refreshed <literal>@Configuration</literal>).</simpara> |
|
</note> |
|
</section> |
|
<section xml:id="_encryption_and_decryption"> |
|
<title>Encryption and Decryption</title> |
|
<simpara>Spring Cloud has an <literal>Environment</literal> pre-processor for decrypting |
|
property values locally. It follows the same rules as the Config |
|
Server, and has the same external configuration via <literal>encrypt.*</literal>. Thus |
|
you can use encrypted values in the form <literal>{cipher}*</literal> and as long as |
|
there is a valid key then they will be decrypted before the main |
|
application context gets the <literal>Environment</literal>. To use the encryption |
|
features in an application you need to include Spring Security RSA in |
|
your classpath (Maven co-ordinates |
|
"org.springframework.security:spring-security-rsa") and you also need |
|
the full strength JCE extensions in your JVM.</simpara> |
|
<simpara>If you are getting an exception due to "Illegal key size" and you are using Sun’s JDK, you need to install the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files. See the following links for more information:</simpara> |
|
<itemizedlist> |
|
<listitem> |
|
<simpara><link xl:href="http://www.oracle.com/technetwork/java/javase/downloads/jce-6-download-429243.html">Java 6 JCE</link></simpara> |
|
</listitem> |
|
<listitem> |
|
<simpara><link xl:href="http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html">Java 7 JCE</link></simpara> |
|
</listitem> |
|
<listitem> |
|
<simpara><link xl:href="http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html">Java 8 JCE</link></simpara> |
|
</listitem> |
|
</itemizedlist> |
|
<simpara>Extract files into JDK/jre/lib/security folder (whichever version of JRE/JDK x64/x86 you are using).</simpara> |
|
</section> |
|
<section xml:id="_endpoints"> |
|
<title>Endpoints</title> |
|
<simpara>For a Spring Boot Actuator application there are some additional management endpoints:</simpara> |
|
<itemizedlist> |
|
<listitem> |
|
<simpara>POST to <literal>/env</literal> to update the <literal>Environment</literal> and rebind <literal>@ConfigurationProperties</literal> and log levels</simpara> |
|
</listitem> |
|
<listitem> |
|
<simpara><literal>/refresh</literal> for re-loading the boot strap context and refreshing the <literal>@RefreshScope</literal> beans</simpara> |
|
</listitem> |
|
<listitem> |
|
<simpara><literal>/restart</literal> for closing the <literal>ApplicationContext</literal> and restarting it (disabled by default)</simpara> |
|
</listitem> |
|
<listitem> |
|
<simpara><literal>/pause</literal> and <literal>/resume</literal> for calling the <literal>Lifecycle</literal> methods (<literal>stop()</literal> and <literal>start()</literal> on the <literal>ApplicationContext</literal>)</simpara> |
|
</listitem> |
|
</itemizedlist> |
|
</section> |
|
</chapter> |
|
<chapter xml:id="_spring_cloud_commons_common_abstractions"> |
|
<title>Spring Cloud Commons: Common Abstractions</title> |
|
<simpara>Patterns such as service discovery, load balancing and circuit breakers lend themselves to a common abstraction layer that can be consumed by all Spring Cloud clients, independent of the implementation (e.g. discovery via Eureka or Consul).</simpara> |
|
<section xml:id="__enablediscoveryclient"> |
|
<title>@EnableDiscoveryClient</title> |
|
<simpara>Commons provides the <literal>@EnableDiscoveryClient</literal> annotation. This looks for implementations of the <literal>DiscoveryClient</literal> interface via <literal>META-INF/spring.factories</literal>. Implementations of Discovery Client will add a configuration class to <literal>spring.factories</literal> under the <literal>org.springframework.cloud.client.discovery.EnableDiscoveryClient</literal> key. Examples of <literal>DiscoveryClient</literal> implementations: are <link xl:href="http://cloud.spring.io/spring-cloud-netflix/">Spring Cloud Netflix Eureka</link>, <link xl:href="http://cloud.spring.io/spring-cloud-consul/">Spring Cloud Consul Discovery</link> and <link xl:href="http://cloud.spring.io/spring-cloud-zookeeper/">Spring Cloud Zookeeper Discovery</link>.</simpara> |
|
<simpara>By default, implementations of <literal>DiscoveryClient</literal> will auto-register the local Spring Boot server with the remote discovery server. This can be disabled by setting <literal>autoRegister=false</literal> in <literal>@EnableDiscoveryClient</literal>.</simpara> |
|
</section> |
|
<section xml:id="_serviceregistry"> |
|
<title>ServiceRegistry</title> |
|
<simpara>Commons now provides a <literal>ServiceRegistry</literal> interface which provides methods like <literal>register(Registration)</literal> and <literal>deregister(Registration)</literal> which allow you to provide custom registered services. <literal>Registration</literal> is a marker interface.</simpara> |
|
<programlisting language="java" linenumbering="unnumbered">@Configuration |
|
@EnableDiscoveryClient(autoRegister=false) |
|
public class MyConfiguration { |
|
private ServiceRegistry registry; |
|
|
|
public MyConfiguration(ServiceRegistry registry) { |
|
this.registry = registry; |
|
} |
|
|
|
// called via some external process, such as an event or a custom actuator endpoint |
|
public void register() { |
|
Registration registration = constructRegistration(); |
|
this.registry.register(registration); |
|
} |
|
}</programlisting> |
|
<simpara>Each <literal>ServiceRegistry</literal> implementation has its own <literal>Registry</literal> implementation.</simpara> |
|
<section xml:id="_serviceregistry_auto_registration"> |
|
<title>ServiceRegistry Auto-Registration</title> |
|
<simpara>By default, the <literal>ServiceRegistry</literal> implementation will auto-register the running service. To disable that behavior, there are two methods. You can set <literal>@EnableDiscoveryClient(autoRegister=false)</literal> to permanently disable auto-registration. You can also set <literal>spring.cloud.service-registry.auto-registration.enabled=false</literal> to disable the behavior via configuration.</simpara> |
|
</section> |
|
<section xml:id="_service_registry_actuator_endpoint"> |
|
<title>Service Registry Actuator Endpoint</title> |
|
<simpara>A <literal>/service-registry</literal> actuator endpoint is provided by Commons. This endpoint relys on a <literal>Registration</literal> bean in the Spring Application Context. Calling <literal>/service-registry/instance-status</literal> via a GET will return the status of the <literal>Registration</literal>. A POST to the same endpoint with a <literal>String</literal> body will change the status of the current <literal>Registration</literal> to the new value. Please see the documentation of the <literal>ServiceRegistry</literal> implementation you are using for the allowed values for updating the status and the values retured for the status.</simpara> |
|
</section> |
|
</section> |
|
<section xml:id="_spring_resttemplate_as_a_load_balancer_client"> |
|
<title>Spring RestTemplate as a Load Balancer Client</title> |
|
<simpara><literal>RestTemplate</literal> can be automatically configured to use ribbon. To create a load balanced <literal>RestTemplate</literal> create a <literal>RestTemplate</literal> <literal>@Bean</literal> and use the <literal>@LoadBalanced</literal> qualifier.</simpara> |
|
<warning> |
|
<simpara>A <literal>RestTemplate</literal> bean is no longer created via auto configuration. It must be created by individual applications.</simpara> |
|
</warning> |
|
<programlisting language="java" linenumbering="unnumbered">@Configuration |
|
public class MyConfiguration { |
|
|
|
@LoadBalanced |
|
@Bean |
|
RestTemplate restTemplate() { |
|
return new RestTemplate(); |
|
} |
|
} |
|
|
|
public class MyClass { |
|
@Autowired |
|
private RestTemplate restTemplate; |
|
|
|
public String doOtherStuff() { |
|
String results = restTemplate.getForObject("http://stores/stores", String.class); |
|
return results; |
|
} |
|
}</programlisting> |
|
<simpara>The URI needs to use a virtual host name (ie. service name, not a host name). |
|
The Ribbon client is used to create a full physical address. See |
|
<link xl:href="https://github.com/spring-cloud/spring-cloud-netflix/blob/master/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonAutoConfiguration.java">RibbonAutoConfiguration</link> |
|
for details of how the <literal>RestTemplate</literal> is set up.</simpara> |
|
<section xml:id="_retrying_failed_requests"> |
|
<title>Retrying Failed Requests</title> |
|
<simpara>A load balanced <literal>RestTemplate</literal> can be configured to retry failed requests. |
|
By default this logic is disabled, you can enable it by adding <link xl:href="https://github.com/spring-projects/spring-retry">Spring Retry</link> to your application’s classpath. The load balanced <literal>RestTemplate</literal> will |
|
honor some of the Ribbon configuration values related to retrying failed requests. If |
|
you would like to disable the retry logic with Spring Retry on the classpath |
|
you can set <literal>spring.cloud.loadbalancer.retry.enabled=false</literal>. |
|
The properties you can use are <literal>client.ribbon.MaxAutoRetries</literal>, |
|
<literal>client.ribbon.MaxAutoRetriesNextServer</literal>, and <literal>client.ribbon.OkToRetryOnAllOperations</literal>. |
|
See the <link xl:href="https://github.com/Netflix/ribbon/wiki/Getting-Started#the-properties-file-sample-clientproperties">Ribbon documentation</link> |
|
for a description of what there properties do.</simpara> |
|
<note> |
|
<simpara><literal>client</literal> in the above examples should be replaced with your Ribbon client’s |
|
name.</simpara> |
|
</note> |
|
</section> |
|
</section> |
|
<section xml:id="_multiple_resttemplate_objects"> |
|
<title>Multiple RestTemplate objects</title> |
|
<simpara>If you want a <literal>RestTemplate</literal> that is not load balanced, create a <literal>RestTemplate</literal> |
|
bean and inject it as normal. To access the load balanced <literal>RestTemplate</literal> use |
|
the <literal>@LoadBalanced</literal> qualifier when you create your <literal>@Bean</literal>.</simpara> |
|
<important> |
|
<simpara>Notice the <literal>@Primary</literal> annotation on the plain <literal>RestTemplate</literal> declaration in the example below, to disambiguate the unqualified <literal>@Autowired</literal> injection.</simpara> |
|
</important> |
|
<programlisting language="java" linenumbering="unnumbered">@Configuration |
|
public class MyConfiguration { |
|
|
|
@LoadBalanced |
|
@Bean |
|
RestTemplate loadBalanced() { |
|
return new RestTemplate(); |
|
} |
|
|
|
@Primary |
|
@Bean |
|
RestTemplate restTemplate() { |
|
return new RestTemplate(); |
|
} |
|
} |
|
|
|
public class MyClass { |
|
@Autowired |
|
private RestTemplate restTemplate; |
|
|
|
@Autowired |
|
@LoadBalanced |
|
private RestTemplate loadBalanced; |
|
|
|
public String doOtherStuff() { |
|
return loadBalanced.getForObject("http://stores/stores", String.class); |
|
} |
|
|
|
public String doStuff() { |
|
return restTemplate.getForObject("http://example.com", String.class); |
|
} |
|
}</programlisting> |
|
<tip> |
|
<simpara>If you see errors like <literal>java.lang.IllegalArgumentException: Can not set org.springframework.web.client.RestTemplate field com.my.app.Foo.restTemplate to com.sun.proxy.$Proxy89</literal> try injecting <literal>RestOperations</literal> instead or setting <literal>spring.aop.proxyTargetClass=true</literal>.</simpara> |
|
</tip> |
|
</section> |
|
<section xml:id="ignore-network-interfaces"> |
|
<title>Ignore Network Interfaces</title> |
|
<simpara>Sometimes it is useful to ignore certain named network interfaces so they can be excluded from Service Discovery registration (eg. running in a Docker container). A list of regular expressions can be set that will cause the desired network interfaces to be ignored. The following configuration will ignore the "docker0" interface and all interfaces that start with "veth".</simpara> |
|
<formalpara> |
|
<title>application.yml</title> |
|
<para> |
|
<screen>spring: |
|
cloud: |
|
inetutils: |
|
ignoredInterfaces: |
|
- docker0 |
|
- veth.*</screen> |
|
</para> |
|
</formalpara> |
|
<simpara>You can also force to use only specified network addresses using list of regular expressions:</simpara> |
|
<formalpara> |
|
<title>application.yml</title> |
|
<para> |
|
<screen>spring: |
|
cloud: |
|
inetutils: |
|
preferredNetworks: |
|
- 192.168 |
|
- 10.0</screen> |
|
</para> |
|
</formalpara> |
|
<simpara>You can also force to use only site local addresses. See <link xl:href="https://docs.oracle.com/javase/8/docs/api/java/net/Inet4Address.html#isSiteLocalAddress--">Inet4Address.html.isSiteLocalAddress()</link> for more details what is site local address.</simpara> |
|
<formalpara> |
|
<title>application.yml</title> |
|
<para> |
|
<screen>spring: |
|
cloud: |
|
inetutils: |
|
useOnlySiteLocalInterfaces: true</screen> |
|
</para> |
|
</formalpara> |
|
</section> |
|
</chapter> |
|
</book> |