create RestTemplate with LoadBalancerInterceptor using @LoadBalanced qualifier.
fixes https://github.com/spring-cloud/spring-cloud-netflix/issues/267
This commit is contained in:
@@ -275,4 +275,54 @@ For a Spring Boot Actuator application there are some additional management endp
|
||||
|
||||
== Spring Cloud Commons: Common Abstractions
|
||||
|
||||
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).
|
||||
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).
|
||||
|
||||
|
||||
=== Spring RestTemplate as a Load Balancer Client
|
||||
|
||||
You can use Ribbon indirectly via an autoconfigured `RestTemplate`
|
||||
when RestTemplate is on the classpath and a `LoadBalancerClient` bean is defined):
|
||||
|
||||
[source,java,indent=0]
|
||||
----
|
||||
public class MyClass {
|
||||
@Autowired
|
||||
private RestTemplate restTemplate;
|
||||
|
||||
public String doOtherStuff() {
|
||||
String results = restTemplate.getForObject("http://stores/stores", String.class);
|
||||
return results;
|
||||
}
|
||||
}
|
||||
----
|
||||
|
||||
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
|
||||
{github-code}/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonAutoConfiguration.java[RibbonAutoConfiguration]
|
||||
for details of how the `RestTemplate` is set up.
|
||||
|
||||
=== Multiple RestTemplate objects
|
||||
|
||||
If you want a `RestTemplate` that is not load balanced, create a `RestTemplate`
|
||||
bean and inject it as normal. To access the load balanced `RestTemplate use
|
||||
the provided `@LoadBalanced` `Qualifier`:
|
||||
|
||||
[source,java,indent=0]
|
||||
----
|
||||
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);
|
||||
}
|
||||
}
|
||||
----
|
||||
Reference in New Issue
Block a user