How to configure load balancing for RestTemplate?
When using RestTemplate for load balancing, it is common to configure it in conjunction with Spring Cloud’s service discovery and load balancing components. Here is a simple configuration example:
- Add dependencies:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency>
- Create a RestTemplate Bean.
@Configuration
public class RestTemplateConfig {
@LoadBalanced
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
- “When the @LoadBalanced annotation is used, it enables load balancing functionality for RestTemplate. RestTemplate will automatically use a service discovery component (such as Eureka) to locate instances of the target service and perform load balancing. Here is an example code snippet:”
@RestController
public class MyController {
@Autowired
private RestTemplate restTemplate;
@GetMapping("/test")
public String test() {
ResponseEntity<String> response = restTemplate.getForEntity("http://my-service/api/test", String.class);
return response.getBody();
}
}
In the example above, RestTemplate will use a service discovery component to locate a service instance named “my-service” and make a load-balanced call. If there are multiple instances, RestTemplate will choose one instance based on the load-balancing algorithm.