apache / dubbo-website

Apache Dubbo documents
https://dubbo.apache.org/
Apache License 2.0
471 stars 792 forks source link

A beggar's version of weight round robin load balance -_- #2879

Open peter-liu97 opened 10 months ago

peter-liu97 commented 10 months ago

Describe the proposal

public class WeightRoundRobinLoadBalance implements LoadBalance {
    private int totalWeight = 0;
    private final List<ServerNode> serverNodeList;

    public WeightRoundRobinLoadBalance(List<ServerNode> serverNodeList) {
        this.serverNodeList = serverNodeList;
        serverNodeList.forEach(p -> totalWeight += p.getWeight());
    }
    @Override
    public ServerNode getServer() {
        ServerNode result = serverNodeList.stream()
                .peek(serverNode -> serverNode.addCurrent(serverNode.getWeight()))
                .max(Comparator.comparingInt(ServerNode::getCurrent)).get();
        result.subtractCurrent(totalWeight);
        return result;
    }
}
public class ServerNode {

    private String ip;

    private Integer weight = 1;

    private Integer current = 0;

    public ServerNode(String ip) {
        this.ip = ip;
    }

    public ServerNode(String ip, Integer weight) {
        this.ip = ip;
        this.weight = weight;
    }

    public void addCurrent(int addNum){
        this.current += addNum;
    }
    public void subtractCurrent(int addNum){
        this.current -= addNum;
    }
}