Spring Boot @LoadBalanced Example

1. Introduction

In a microservices architecture, it's common to have multiple instances of a service running. Spring Boot provides the @LoadBalanced annotation to automatically integrate a client-side load-balancer when making REST calls to other services. This ensures that requests are evenly distributed across the available service instances, improving fault tolerance and scalability. In this blog post, we'll create a simple example to illustrate the use of the @LoadBalanced annotation in a Spring Boot application.

Key Points:

1. @LoadBalanced is used with RestTemplate to enable client-side load balancing in Spring Boot applications.

2. It allows RestTemplate to work with service discovery to call services registered with Eureka, Consul, or other service registries.

3. The load balancer intercepts calls to services and applies a strategy, such as round-robin, to distribute the load.

4. @LoadBalanced can also be used with WebClient, which is the non-blocking alternative to RestTemplate.

5. To use this annotation, Spring Cloud LoadBalancer with a compatible service registry must be part of your application's classpath.

2. Implementation Steps

1. Add the Spring Cloud Starter LoadBalancer dependency to your project.

2. Define a RestTemplate bean and annotate it with @LoadBalanced.

3. Autowire the RestTemplate in your service class.

4. Make service calls using RestTemplate and pass the service name instead of the host and port.

5. Start the application and make a call to the REST endpoint that uses the RestTemplate.

3. Implementation Example

// Step 1: Add the Spring Cloud LoadBalancer dependency to your Maven or Gradle build file

// Step 2: Define a `RestTemplate` bean with the `@LoadBalanced` annotation
@Configuration
public class AppConfig {

    @Bean
    @LoadBalanced
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

// Step 3: Autowire the `RestTemplate` in your service class to use it
@Service
public class UserService {

    private final RestTemplate restTemplate;

    public UserService(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    public String getUserData(String userId) {
        // Using the service name 'user-service' instead of an actual URL
        return restTemplate.getForObject("http://user-service/users/" + userId, String.class);
    }
}

// Step 4: Create a REST controller that uses the UserService
@RestController
public class UserController {

    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping("/users/{userId}")
    public String getUser(@PathVariable String userId) {
        return userService.getUserData(userId);
    }
}

// Step 5: Run the application
@SpringBootApplication
public class LoadBalancedApplication {

    public static void main(String[] args) {
        SpringApplication.run(LoadBalancedApplication.class, args);
    }
}

// After running the application, you can call your controller endpoint to get the user data.

Output:

// The output will depend on the response from the 'user-service' which is being load balanced.
// If 'user-service' is running properly, it should return the user data for the given userId.

Explanation:

1. @LoadBalanced: This annotation is applied to the RestTemplate bean to enable client-side load balancing.

2. RestTemplate: This is the Spring class used for synchronous client-side HTTP access. It's configured to use the load balancer to resolve service names to actual HTTP endpoints.

3. UserService: A service class that uses RestTemplate to make calls to the 'user-service'.

4. getUserData(String userId): This method in UserService demonstrates how to make a load-balanced call using a logical service name.

5. UserController: A controller that exposes an endpoint to fetch user data.

6. @RestController and @GetMapping: Spring MVC annotations used to create RESTful controllers and map HTTP requests to handler methods.

7. LoadBalancedApplication: The main class of the Spring Boot application that runs the application and includes all the configuration.

8. SpringApplication.run(): This method bootstraps the application, starting the embedded server, auto-configuring Spring components, and applying the @LoadBalanced configuration.


Comments