Spring Cloud Alibaba - 07 Ribbon application and built-in load balancing algorithm

Article catalogue

Ribbon integration Trilogy

Here we practice load balancing through the Ribbon component [the default load balancing algorithm is polling]


step1 do dependency



Step 2 annotation (add @ LoadBalanced annotation on RestTemplate)

public class WebConfig {

    public RestTemplate restTemplate(){
        return new RestTemplate();
Step3 configuration file

Here is the configuration file of Nacos, and the configuration of Ribbon is not configured for the time being

    name: artisan-order-center


As a service provider, you only need to register with Nacos without integrating the Ribbon and start multiple load policies of the test Ribbon.

public class ProductInfoController {

    private Integer port;

    private ProductInfoMapper productInfoMapper;

    public Object selectProductInfoById(@PathVariable("productNo") String productNo) {
        log.info("{} Requested",port);
        ProductInfo productInfo = productInfoMapper.selectProductInfoById(productNo);
        return productInfo;



Three separate requests

The log is as follows

It can be guessed that the default policy is polling algorithm

Modify the Ribbon's default load policy

Request three times

Ribbon's built-in load balancing algorithm

Class relationship (AbstractLoadBalancerRule abstract class of IRule interface)

It can be seen that the policy design pattern is adopted, and the public ones are written in the abstract class

Load balancing algorithm


Randomly select a Server


For the on-board retry mechanism of the selected load balancing policy, if the server is not selected successfully within a configured time period, it has been trying to select an available server by using the subRule method


Poll selection, poll index, and select the Server corresponding to the index


Filter out the back-end servers marked as circuit tripped that have failed to connect all the time, and filter out those high concurrency back-end servers, or use an availability predicate to include the logic of filtering servers. In fact, it is to check the running status of each server recorded in status


Select a Server with the smallest concurrent request and inspect the servers one by one. If the Server is tripped, skip it.


According to the response time weighting, the longer the response time, the smaller the weight, and the lower the possibility of being selected;

ZoneAvoidanceRule (default)

Judge the performance of the Zone where the Server is located and the availability of the Server. Select the Server. If there is no Zone, the class is polling.

Source code


Added by pibebueno on Thu, 03 Feb 2022 13:23:11 +0200