dubbo负载算法之加权轮询算法

轮询是一种无状态负载均衡算法,实现简单,适用于每台服务器性能相近的场景下。但现实情况下,我们并不能保证每台服务器性能均相近。如果我们将等量的请求分配给性能较差的服务器,这显然是不合理的。因此,这个时候我们需要对轮询过程进行加权,以调控每台服务器的负载。经过加权后,每台服务器能够得到的请求数比例,接近或等于他们的权重比。比如服务器 A、B、C 权重比为 5:2:1。那么在8次请求中,服务器 A 将收到其中的5次请求,服务器 B 会收到其中的2次请求,服务器 C 则收到其中的1次请求。以上就是加权轮询的算法思想;

因为dubbo版本的不同负载算法不同

一、dubbo2.5.9

这个版本的轮询思想是在所有权重之和的次数内的负载是安装权重之比分配的:

意思是如果两个节点1权重为100,2节点权重为200,权重之和300,前两百次负载交替轮询,后一百次都在2节点上;

如果三个节点1权重100.2权重200,3权重为300,则前300次负载交替轮询,300-500次则2和3节点交替轮询,最后100次则都在3节点上

public class RoundRobinLoadBalance extends AbstractLoadBalance {
    public static final String NAME = "roundrobin";
    //用于记录每个服务调用的次数
    private final ConcurrentMap<String, AtomicPositiveInteger> sequences = new ConcurrentHashMap();

    public RoundRobinLoadBalance() {
    }

    protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {
        String key = ((Invoker)invokers.get(0)).getUrl().getServiceKey() + "." + invocation.getMethodName();
        int length = invokers.size();
        int maxWeight = 0;
        int minWeight = 2147483647;
        LinkedHashMap<Invoker<T>, RoundRobinLoadBalance.IntegerWrapper> invokerToWeightMap = new LinkedHashMap();
        int weightSum = 0;

        int currentSequence;
        // 下面这个循环主要用于查找最大和最小权重,计算权重总和等
        for(int i = 0; i < length; ++i) {
            //获取当前服务节点的权重
            currentSequence = this.getWeight((Invoker)invokers.get(i), invocation);
            //获取最大服务节点的权重
            maxWeight = Math.max(maxWeight, currentSequence);
            //获取最小服务节点的权重
            minWeight = Math.min(minWeight, currentSequence);
            if (currentSequence > 0) {
                // 将 weight 封装到 IntegerWrapper 中
                invokerToWeightMap.put(invokers.get(i), new RoundRobinLoadBalance.IntegerWrapper(currentSequence));
                weightSum += currentSeque
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值