Spring Cloud Ribbon: Hands‑On Guide to Client‑Side Load Balancing

This article walks through the background of Spring Cloud Ribbon, explains its client‑side load‑balancing role, provides step‑by‑step code to create multiple provider services and a consumer that uses Ribbon, and shows how to configure different balancing algorithms and retry mechanisms.

Pan Zhi's Tech Notes
Pan Zhi's Tech Notes
Pan Zhi's Tech Notes
Spring Cloud Ribbon: Hands‑On Guide to Client‑Side Load Balancing

1. Background

In the previous article we introduced Eureka, the service‑registration and discovery component of Spring Cloud. This article builds on that knowledge to explore another core component, Ribbon.

2. Ribbon Overview

Spring Cloud Ribbon is a client‑side load‑balancing tool built on Netflix Ribbon. It supplies client load‑balancing algorithms (e.g., round‑robin, random) that let a consumer select a service instance from a list cached from Eureka.

In production a service is usually deployed as a cluster of identical instances. Traditional architectures place a load balancer (such as Nginx) in front of the servers; Ribbon moves the balancing logic to the client, periodically pulling the instance list from Eureka and choosing an address according to the configured rule.

Client‑side balancing reduces request latency because the call goes directly to the selected instance.

3. Practical Implementation

3.1 Create Multiple Service Providers

Create a Spring Boot project named eureka-provider-1 and add the following dependencies in pom.xml:

<parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>1.5.4.RELEASE</version>
</parent>

<dependencies>
  <dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-eureka</artifactId>
  </dependency>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
  </dependency>
</dependencies>

<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-dependencies</artifactId>
      <version>Edgware.SR3</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>

Add the annotation @EnableDiscoveryClient to the main class and create a simple controller that returns a greeting:

@EnableDiscoveryClient
@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
@RestController
public class HelloController {
    @GetMapping("/hello")
    public String index() {
        System.out.println("收到客户端发起的rpc请求!");
        return "hello,我是服务提供方 provider 1";
    }
}

Configure application.properties:

spring.application.name=eureka-provider
server.port=9011
# Multiple Eureka servers can be separated by ','
eureka.client.serviceUrl.defaultZone=http://localhost:8001/eureka/

Repeat the same steps for a second project eureka-provider-2, changing the returned string to “hello,我是服务提供方 provider 2”.

3.2 Create the Consumer and Integrate Ribbon

Create a Spring Boot project named eureka-consumer-ribbon and add the Ribbon starter dependency:

<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-ribbon</artifactId>
</dependency>

Define a RestTemplate bean annotated with @LoadBalanced to enable client‑side load balancing:

@EnableDiscoveryClient
@SpringBootApplication
public class Application {
    @Bean
    @LoadBalanced
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

Create a controller that calls the provider using the logical service name:

@RestController
public class HelloController {
    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/rpc")
    public String rpc() {
        // The service name will be replaced by a chosen instance according to the load‑balancing rule
        String url = "http://eureka-provider/hello";
        String result = restTemplate.getForObject(url, String.class);
        return "发起远程调用,收到返回的信息:" + result;
    }
}

Configure the consumer:

spring.application.name=eureka-consumer
server.port=9002

eureka.client.serviceUrl.defaultZone=http://localhost:8001/eureka/

Start the Eureka server, both provider services, and the consumer. Access http://localhost:9002/rpc repeatedly; the response alternates between the two provider messages, confirming round‑robin load balancing.

4. Advanced Ribbon Features

4.1 Configuring Load‑Balancing Rules

Ribbon supports several algorithms. The default is RoundRobinRule. Other available rules are:

RandomRule – selects a random server

BestAvailableRule – selects the server with the fewest concurrent requests

WeightedResponseTimeRule – gives higher weight to servers with shorter response times

AvailabilityFilteringRule – filters out faulty servers before applying round‑robin

RetryRule – retries the same server within a timeout before switching

ZoneAvoidanceRule – selects the best server based on zone performance

To change the rule, set the property ribbon.NFLoadBalancerRuleClassName in application.properties. Example using the random algorithm:

# Use random load‑balancing algorithm
eureka-consumer-ribbon.ribbon.NFLoadBalancerRuleClassName=com.netflix.loadbalancer.RandomRule

Custom rules can be created by implementing the IRule interface.

4.2 Configuring Retry Mechanism

Ribbon can automatically retry failed requests. The following properties control retry behavior for the consumer:

# Enable retry
spring.cloud.loadbalancer.retry.enabled=true
# Connection timeout (ms)
eureka-consumer-ribbon.ribbon.ConnectTimeout=250
# Read timeout (ms)
eureka-consumer-ribbon.ribbon.ReadTimeout=1000
# Max retries on the same server
eureka-consumer-ribbon.ribbon.MaxAutoRetries=1
# Max retries on the next server
eureka-consumer-ribbon.ribbon.MaxAutoRetriesNextServer=2
# Retry on all operations
eureka-consumer-ribbon.ribbon.OkToRetryOnAllOperations=true

If a request fails, Ribbon first retries up to MaxAutoRetries on the same instance; if those attempts are exhausted, it switches to another instance and retries up to MaxAutoRetriesNextServer. If all retries fail, an error is returned.

5. Conclusion

Ribbon is one of the most important components in the Spring Cloud ecosystem, providing client‑side load‑balancing management. Although Netflix has stopped maintaining the original library, it remains a valuable learning case for quickly mastering Spring Cloud’s architecture.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

microservicesload balancingspring-booteurekaSpring CloudRibbon
Pan Zhi's Tech Notes
Written by

Pan Zhi's Tech Notes

Sharing frontline internet R&D technology, dedicated to premium original content.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.