Client-Side Load Balancing with Spring Cloud Ribbon
Spring Cloud Ribbon is a client-side load balancing library built on top of Netflix Ribbon. It distributes incoming HTTP requests across multiple service instances registered in a service registry—such as Eureka—to prevent overloading any single node. When multiple replicas of a service (e.g., eureka-client-8762 and eureka-client-8763) are deployed and registered with Eureka, Ribbon transparently selects an appropriate instance for each outbound request using configurable strategies. Ribbon supports out-of-the-box algorithms—including round-robin (default), random, and weighted response time—and allows developers to plug in custom logic via implementations of IRule. #### 2. Integration Example
Project Setup
We assume two upstream services—user-service (running on ports 8762 and 8763)—are already registered in Eureka at http://localhost:8761/eureka. Now we build a consumer service named load-balancer-consumer (port 8764) that uses Ribbon to route requests. ##### Maven Depandencies
Add the following to pom.xml: ```
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
##### Configuration Fille
`application.yml`: ```
server:
port: 8764
spring:
application:
name: load-balancer-consumer
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka
Main Application Class
@SpringBootApplication
@EnableEurekaClient
public class LoadBalancerConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(LoadBalancerConsumerApplication.class, args);
}
}
RestTemplate Configuration with Load Balancing
Create RestTemplateConfig.java under com.dzbiao.config: ```
@Configuration
public class RestTemplateConfig {
@Bean
@LoadBalanced
public RestTemplate createBalancedClient() {
return new RestTemplate();
}
}
##### Controller for Testing
In the same package as the main class, add: ```
@RestController
@RequestMapping("/api")
public class UserController {
private final RestTemplate balancedClient;
public UserController(RestTemplate balancedClient) {
this.balancedClient = balancedClient;
}
@GetMapping("/user")
public String fetchUserInfo() {
// 'user-service' resolves to available Eureka instances
return balancedClient.getForObject("http://user-service/user", String.class);
}
}
Verification
After launching all four applications (Eureka server on 8761, two user-service instances on 8762/8763, and the consumre on 8764), access http://localhost:8764/api/user. Repeated calls will alternate responses indicating either 8762 or 8763, confirming round-robin distribution managed by Ribbon.