Spring cloud (5): Ribbon load balancing mechanism

Time:2021-1-14

1. Test custom load balancing rules

1.1 server

To create a first boot project:

pom:

4.0.0
    org.crazyi.cloud
    first-boot
    0.0.1-SNAPSHOT
    
    
        
            org.springframework.boot
            spring-boot-starter-web
            1.5.7.RELEASE

Person:

package org.crazyit.cloud;

public class Person {

    private Integer id;
    private String name;
    private Integer age;
    private String message;
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
    
}

MyController:

package org.crazyit.cloud;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class MyController {

    @GetMapping("/hello")
    @ResponseBody
    public String hello() {
        return "Hello World";
    }
}

MyRestController:

package org.crazyit.cloud;

import javax.servlet.http.HttpServletRequest;

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyRestController {

    @RequestMapping(value = "/person/{id}", method = RequestMethod.GET, 
            produces = MediaType.APPLICATION_JSON_VALUE)
    public Person getPerson(@PathVariable Integer id, HttpServletRequest request) {
        Person p = new Person();
        p.setId(id);
        p.setName("angus");
        p.setAge(30);
        p.setMessage(request.getRequestURL().toString());
        return p;
    }
}

FirstApp:

package org.crazyit.cloud;

import java.util.Scanner;

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;

@SpringBootApplication
public class FirstApp {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String port = scan.nextLine();
        new SpringApplicationBuilder(FirstApp.class).properties("server.port=" + port).run(args);
        
    }

}

1.2 client

Create project user ribbon:

Direct use:

LBMain:

package org.crazyit.cloud;

import java.util.ArrayList;
import java.util.List;

import com.netflix.loadbalancer.BaseLoadBalancer;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;

public class LBMain {

    public static void main(String[] args) {
        ILoadBalancer lb = new BaseLoadBalancer();
        List servers = new ArrayList();
        servers.add(new Server("localhost", 8080));
        servers.add(new Server("localhost", 8081));
        
        lb.addServers(servers);
        for(int i = 0; i < 10; i++) {
            Server s = lb.chooseServer(null);
            System.out.println(s);
        }
    }

}

Use rule:

MyRule:

package org.crazyit.cloud;

import java.util.List;
import java.util.Random;

import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.Server;

public class MyRule implements IRule {
    
    private ILoadBalancer lb;

    public Server choose(Object key) {
        Random r = new Random();
        int rNum = r.nextInt(10);
        
        List servers = lb.getAllServers();
        
        if(rNum > 7) {
            return getServerByPort(servers, 8081);
        }
        return getServerByPort(servers, 8080);
    }
    
    private Server getServerByPort(List servers, int port) {
        for(Server s : servers) {
            if(s.getPort() == port) {
                return s;
            }
        }
        return null;
    }

    public void setLoadBalancer(ILoadBalancer lb) {
        this.lb = lb;
    }

    public ILoadBalancer getLoadBalancer() {
        return this.lb;
    }

}

TestMyRule:

package org.crazyit.cloud;

import java.util.ArrayList;
import java.util.List;

import com.netflix.loadbalancer.BaseLoadBalancer;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;

public class TestMyRule {

    public static void main(String[] args) {
        BaseLoadBalancer lb = new BaseLoadBalancer();
        MyRule rule = new MyRule();
        rule.setLoadBalancer(lb);
        lb.setRule(rule);
        
        List servers = new ArrayList();
        servers.add(new Server("localhost", 8080));
        servers.add(new Server("localhost", 8081));
        lb.addServers(servers);
        for(int i = 0; i < 10; i++) {
            Server s = lb.chooseServer(null);
            System.out.println(s);
        }
    }

}

TestRibbon:

package org.crazyit.cloud;

import com.netflix.client.ClientFactory;
import com.netflix.client.http.HttpRequest;
import com.netflix.client.http.HttpResponse;
import com.netflix.config.ConfigurationManager;
import com.netflix.niws.client.http.RestClient;

public class TestRibbon {

    public static void main(String[] args) throws Exception {
        ConfigurationManager.getConfigInstance().setProperty(
                  "my-client.ribbon.listOfServers", "localhost:8080,localhost:8081");
        ConfigurationManager.getConfigInstance().setProperty(
                  "my-client.ribbon.NFLoadBalancerRuleClassName", MyRule.class.getName());
        
        //Get rest request client
        RestClient client = (RestClient) ClientFactory
                .getNamedClient("my-client");
        //Create request instance
        HttpRequest request = HttpRequest.newBuilder().uri("/person/1").build();
        //Send 10 requests to the server
        for (int i = 0; i < 10; i++) {
            HttpResponse response = client.executeWithLoadBalancer(request);
            String result = response.getEntity(String.class);
            System.out.println(result);
        }
    }

}