RestTemplate
Can be automatically configured to use the Ribbon. Create RestTemplate
RestTemplate
@Bean
and use qualifiers to create load balancing @LoadBalanced
.
Warning: No longer created with automatic configuration
RestTemplate
Bean. It must be created by a single application.
@Configuration Public classmyconfiguration {@LoadBalanced @Bean resttemplate resttemplate () {return Newresttemplate (); }} Public classMyClass {@AutowiredPrivateresttemplate resttemplate; Publicstring Dootherstuff () {string results= Resttemplate.getforobject ("Http://stores/stores", String.class); returnresults; }}
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 more information about how to set up RestTemplate
, 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.
Spring resttemplate as a load balancer client