RestTemplate can be automatically configured to use the Ribbon. Create RestTemplate RestTemplate @Bean and use @LoadBalanced qualifiers to create load balancing.
| Warning |
The bean is no longer created by automatic configuration RestTemplate . It must be created by a single application. |
@Configurationpublic 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; }}
the URI needs to use the virtual hostname (that is, the service name, not the host name). The Ribbon client is used to create a complete physical address. for RestTemplate More information about how to set up, see ribbonautoconfiguration.
Retry a failed request
Load Balancing RestTemplate can configure requests for retry failures. by Default, this logic is disabled, and you can enable it by adding Spring retry to the application's Classpath . Load Balancing RestTemplate will conform to some of the Ribbon configuration values related to retry failed requests. If you want to disable retry logic by using Spring retry in the classpath, you can set the spring.cloud.loadbalancer.retry.enabled=false . The properties that you can use are client.ribbon.MaxAutoRetries , client.ribbon.MaxAutoRetriesNextServer and client.ribbon.OkToRetryOnAllOperations . See the Ribbon documentation for details about the properties.
| Attention |
The above example client should be replaced with your ribbon client name. |
Source Source
Spring Cloud Commons Tutorial (ii) Spring resttemplate as a load balancer client