A RestTemplate bean can be annotated with @LoadBalanced to mark it for customization with the RibbonClientHttpRequestFactory so that Eureka discovered names are resolved to real resource URLs. See Microservices with Spring - Load balanced RestTemplate.
In Spring Boot 1.4, it is now recommended to inject a RestTemplateBuilder bean into Rest client classes rather than use RestTemplate directly. See Spring Boot Reference - Calling REST services.
When a Rest client is created with a RestTemplateBuilder, the RestTemplate is not automatically customized with the RibbonClientHttpRequestFactory and names are not resolved against Eureka. Ideally, this customization should happen when Ribbon Http client is enabled (property ribbon.http.client.enabled).
I've used this as a workaround - this is a possible way of fixing: Spanners-mvc RestClientConfig
Comment From: spencergibb
Integration with the builder is a good idea. RibbonClientHttpRequestFactory is no longer the default. It does not support some basic http methods.
Comment From: ryanjbaxter
Why not just do this?
@Bean
@LoadBalanced
public RestTemplate restTemple() {
return new RestTemplateBuilder().build();
}
Comment From: spencergibb
Closing this due to inactivity. Please re-open if there's more to discuss.
Comment From: simpletasks
Beans can be created in a static way annotating classes or configuration methods.
But also in a dynamic way with methods registerBean.
When I create RestTemplate bean in a dynamic way, everything works as expected except LoadBalancing.
A clean, and simple way to add load-balancing behavior to dynamically created RestTemplate is by the usage of LoadBalanced annotation on RestTemplateBuilder. RestTemplateBuilder can be injected where needed and RestTemplate instances can be created from it, with load balancing behavior.
I would like to see LoadBalanced annotation working with RestTemplateBuilder, to be able to create RestTemplate instances on the fly with load-balanced behavior.
For now, what is the alternative approach to having dynamically created RestTemplate with load-balanced behavior?