@Autowired
+private DiscoveryClient discoveryClient;
+
+public String serviceUrl() {
+ InstanceInfo instance = discoveryClient.getNextServerFromEureka("STORES", false);
+ return instance.getHomePageUrl();
+}
+From 2784dc6f5a0525eaffe270ace55cd6ea4407fe90 Mon Sep 17 00:00:00 2001
From: Dave Syer
-
-
-
-
The default strategy for locating property sources is to clone a git
-repository (at "spring.cloud.config.server.uri") and use it to
+repository (at "spring.cloud.config.server.git.uri") and use it to
initialize a mini SpringApplication. The mini-application’s
Environment is used to enumerate property sources and publish them
via a JSON endpoint. The service has resources in the form:
@EnableConfigServer annotation.
Where do you want to store the configuration data for the Config
+Server? The strategy that governs this behaviour is the
+EnvironmentRepository, serving Environment objects. This
+Environment is a shallow copy of the domain from the Spring
+Environment (including propertySources as the main feature). The
+default implementation of EnvironmentRepository uses a Git backend,
+which is very convenient for managing upgrades and physical
+environments, and also for auditing changes. To change the location of
+the repository you can set the "spring.cloud.config.server.uri"
+configuration property in the Config Server (e.g. in
+application.yml). If you set it with a file: prefix it should work
+from a local repository so you can get started quickly and easily
+without a server (it doesn’t matter if it’s not bare because the
+Config Server never makes changes to the "remote" repository). To
+scale the Config Server up and make it highly available, however, you
+would need to have all instances of the server pointing to the same
+repository, so only a shared file system would work.
There is also a "native" profile in the Config Server that doesn’t use +Git, but just loads the config files from the local classpath (or +anywhere else you want to point to with +"spring.cloud.config.server.locations"). To use the native profile +just launch the Config Server with "spring.profiles.active=native". In +the native profile the repository only has the "current" set of +configuration files, so the "label" specification in the HTTP +resources is ignored (i.e. it’s like always pulling from "master" in +the Git implementation).
+The Config Server can be embedded in another web application by +setting "spring.cloud.config.server.prefix" (default empty), e.g. to +"/config". If you do that, then you probably want to bootstrap the app +containing the Config Server from the same remote repository from +which all the other remote apps get their configuration properties +(otherwise it is just a normal Spring Boot application since it won’t +have a Config Server to contact when it starts). To do that you just +need to make sure that the (optional) property +"spring.cloud.config.server.bootstrap" is "true".
+You are free to secure your Config Server in any way that makes sense
@@ -933,7 +938,7 @@ your application.yml for the Config Server:
The Config Server runs best as a standalone application, but if you need to you can embed it in another application. Just use the @@ -1442,7 +1447,50 @@ ID, or VIP).
See EurekaInstanceConfigBean and EurekaClientConfigBean for more details of the configurable options.
Once you have an app that is @EnableEurekaClient you can use it to
+discover service instances from the Eureka Server. One way to do that is to use the native DiscoveryClient, e.g.
@Autowired
+private DiscoveryClient discoveryClient;
+
+public String serviceUrl() {
+ InstanceInfo instance = discoveryClient.getNextServerFromEureka("STORES", false);
+ return instance.getHomePageUrl();
+}
+|
+ Tip
+ |
+
+
+
+Don’t use the
+
+=== Alternatives to the DiscoveryClient +
+
+You don’t have to use the raw Netflix
+
=== Why is it so Slow to Register a Service? +Being an instance also involves a periodic heartbeat to the registry
(via the client’s
+
-
-
-== Service Discovery: Eureka Server
- Service Discovery: Eureka Server-Example eureka server: /eureka/*.
Eureka background reading: see flux capacitor and google group discussion.
-
You can run the Eureka server as an executable JAR (or WAR) using the Spring @@ -1532,12 +1574,11 @@ springBoot { } |
-
=== High Availability, Zones and Regions
The Eureka server does not have a backend store, but the service instances in the registry all have to send heartbeats to keep their @@ -1551,9 +1592,9 @@ go to the registry for every single request to a service).
the service will run and work, but it will shower your logs with a lot of noise about not being able to register with the peer.=== Standalone Mode
The combination of the two caches (client and server) and the heartbeats make a standalone Eureka server fairly resilient to @@ -1582,9 +1623,9 @@ eureka:
Notice that the serviceUrl is pointing to the same host as the local
instance.
=== Peer Awareness
Eureka can be made even more resilient and available by running multiple instances and asking them to register with each other. In @@ -1632,12 +1673,9 @@ the registrations amongst themselves. If the peers are physically separated (inside a data centre or between multiple data centres) then the system can in principle survive split-brain type failures.
== Circuit Breaker: Hystrix Clients
Netflix has created a library called Hystrix that implements the circuit breaker pattern. In a microservice architecture it is common to have multiple layers of service calls.
The @HystrixCommand is provided by a Netflix contrib library called
-"javanica". Spring Cloud automatically wraps Spring beans with that
+"javanica".
+Spring Cloud automatically wraps Spring beans with that
annotation in a proxy that is connected to the Hystrix circuit
breaker. The circuit breaker calculates when to open and close the
circuit, and what to do in case of a failure.
To configure the @HystrixCommand you can use the commandProperties
+attribute with a list of @HystrixProperty annotations. See
+here
+for more details. See the Hystrix wiki
+for details on the properties available.
The state of the connected circuit breakers are also exposed in the
/health endpoint of the calling application.
== Circuit Breaker: Hystrix Dashboard
One of the main benefits of Hystrix is the set of metrics it gathers about each HystrixCommand. The Hystrix Dashboard displays the health of each circuit breaker in an efficient manner.
To run the Hystrix Dashboard annotate your Spring Boot main class with @EnableHystrixDashboard. You then visit /hystrix/index.html and point the dashboard to an individual instances /hystrix.stream endpoint in a Hystrix client application.
=== Turbine
+Looking at an individual instances Hystrix data is not very useful in terms of the overall health of the system. Turbine is an application that aggregates all of the relevant /hystrix.stream endpoints into a combined /turbine.stream for use in the Hystrix Dashboard. Individual instances are located via Eureka. Running Turbine is as simple as annotating your main class with the @EnableTurbine annotation.
The clusterName can be customized by a SPEL expression in turbine.clusterNameExpression. For example, turbine.clusterNameExpression=aSGName would get the clustername from the AWS ASG name.
== Declarative REST Client: Feign
Feign is a declarative web service client. It makes writing web service clients easier. To use Feign create an interface and annotate it. It has pluggable annotation support including Feign annotations and JAX-RS annotations. Feign also supports pluggable encoders and decoders. Spring Cloud adds support for Spring MVC annotations and for using the same HttpMessageConverters used by default in Spring Web. Spring Cloud integrates Ribbon and Eureka to provide a load balanced http client when using Feign.
public interface StoreClient {
@RequestMapping(method = RequestMethod.GET, value = "/stores")
- Stores getStores();
+ List<Store> getStores();
@RequestMapping(method = RequestMethod.POST, value = "/stores/{storeId}", consumes = "application/json")
Store update(@PathParameter("storeId") Long storeId, Store store);
}
== Client Side Load Balancer: Ribbon
Usage of LoadBalancerClient directly:
== External Configuration: Archaius
Archaius 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 Apache Commons Configuration project. It allows updates to configuration by either polling a source for changes or for a source to push changes to the client. Archaius uses Dynamic<Type>Property classes as handles to properties.
Archaius has its own set of configuration files and loading priorities. Spring applications should generally not use Archaius directly., but the need to configure the Netflix tools natively remains. Spring Cloud has a Spring Environment Bridge so Archaius can read properties from the Spring Environment. This allows Spring Boot projects to use the normal configuration toolchain, while allowing them to configure the Netflix tools, for the most part, as documented.
== Router and Filter: Zuul
Routing in an integral part of a microservice architecture. For example, / may be mapped to your web application, /api/users is mapped to the user service and /api/shop is mapped to the shop service. Zuul is a JVM based router and server side load balancer by Netflix.
Zuul’s rule engine allows rules and filters to be written in essentially any JVM language, with built in support for Java and Groovy.
=== Embedded Zuul Reverse Proxy
+Spring Cloud has created an embedded Zuul proxy to ease the development of a very common use case where a UI application wants to proxy calls to one or more back end services. To enable it, annotate a Spring Boot main class with @EnableZuulProxy. This forwards local calls to /proxy/* to the appropriate service. The proxy uses Ribbon to locate an instance to forward to via Eureka. Forwarding to the service is protected by a Hystrix circuit breaker. Rules are configured via the Spring environment. The Config Server is an ideal place for the Zuul configuration. Zuul Embedded Proxy configuration rules look like the following:
This means that http calls to /proxy/users get forwarded to the users service. This proxy configuration is useful for services that host a user interface to proxy to the backend services it requires. By default, the proxy mapping gets stripped from the request before forwarding.
=== Standalone Zuul Server
Spring Cloud has created a standalone Zuul server. To enable it, annotate a Spring Boot main class with @EnableZuulServer. This routes all calls to the appropriate service. The server uses Ribbon to locate an instance to forward to via Eureka. Forwarding to the service is protected by a Hystrix circuit breaker. Rules are configured via the Spring environment. The Config Server is an ideal place for the Zuul configuration. Zuul Server configuration rules look like the following:
Since zuul, by default, intercepts all requests (/*), to enable actuator, you should set the management.port.
To use the Spring Boot error facilities while using the standalone Zuul server, please set the following properties
# moves the Spring Dispatch Servlet to a path below `/`
+server:
+ servletPath: /app
+# sets the error path to use the Dispatch Servlet to resolve the error view
+error:
+ path: ${server.servletPath}/error
+= Spring Cloud Cluster
+Spring Cloud Cluster offers a set of primitives for building "cluster" features into a distributed system. Example are leadership election, -consistent storage of cluster state, global locks and one-time tokens. +consistent storage of cluster state, global locks and one-time tokens.
= Spring Platform Bus +:toc:
Spring Cloud Bus links nodes of a distributed system with a lightweight message broker. This can then be used to broadcast state changes (e.g. configuration changes) or other management instructions. A key idea is that the Bus is like a distributed Actuator for a Spring Boot application that is scaled out, but it can also be used as a communication channel between apps. The only implementation currently is with an AMQP broker as the transport, but the same basic feature set (and some more depending on the transport) is on the roadmap for other transports.
== Quick Start
Spring Cloud Bus works by adding Spring Boot autconfiguration if it detects itself on the classpath. All you need to do to enable the bus is to add spring-cloud-starter-bus-amqp to your dependency management and Spring Cloud takes care of the rest. Make sure RabbitMQ is available and configured to provide a ConnectionFactory: running on localhost you shouldn’t have to do anything, but if you are running remotely use Spring Cloud Connectors, or Spring Boot conventions to define the broker credentials, e.g.
The bus currently supports sending messages to all nodes listening or all nodes for a particular service (as defined by Eureka). More selector criteria will be added in the future (ie. only service X nodes in data center Y, etc…). The http endpoints are under the /bus/* actuator namespace. There are currently two implemented. The first, /bus/env, sends key/values pairs to update each nodes Spring Environment. The second, /bus/refresh, will reload each application’s configuration, just as if they had all been pinged on their /refresh endpoint.
= Spring Boot Cloud CLI
Spring Boot command line features for +Spring Cloud.
== Installation
To install, make sure you have @@ -2032,12 +2078,13 @@ $ gvm use springboot 1.1.8.RELEASE $ spring install org.springframework.cloud:spring-cloud-cli:1.0.0.BUILD-SNAPSHOT
= Spring Cloud Security +:github-base: https://github.com/spring-cloud +:security-base: https://github.com/spring-cloud/spring-cloud-security
Spring Cloud Security offers a set of primitives for building secure applications and services with minimum fuss. A declarative model which can be heavily configured externally (or centrally) lends itself to the implementation of large systems of co-operating, remote components, @@ -2045,14 +2092,14 @@ usually with a central indentity management service. It is also extremely easy to use in a service platform like Cloud Foundry. Building on Spring Boot and Spring Security OAuth2 we can quickly create systems that implement common patterns like single sign on, token relay and token -exchange. +exchange.
== Quickstart
+=== OAuth Single Sign On
Here’s a Spring Cloud "Hello World" app with HTTP Basic authentication and a single user account:
@@ -2155,9 +2202,9 @@ credentials of a registered client in Cloud Foundry. It’s quite hard to get a Cloud Foundry client registration for testing (but please ask at support@run.pivotal.io if you want one on PWS).=== OAuth Protected Resource
You want to protect an API resource with an OAuth2 token? Here’s a simple example (paired with the client above):
@@ -2190,9 +2237,9 @@ class Application { preferTokenInfo: false=== Token Relay
If your app has a Spring @@ -2229,7 +2276,7 @@ correct header.
traditional app), and that has some autoconfiguration for aZuulFilter, which itself is activated because Zuul is on the
classpath (via @EnableZuulProxy). The
-filter
+{security-base}/tree/master/src/main/java/org/springframework/cloud/security/proxy/OAuth2TokenRelayFilter.java[filter]
just extracts an access token from the currently authenticated user,
and puts it in a request header for the downstream requests.