关于dubbo:聊聊dubbogo的randomLoadBalance

3次阅读

共计 1644 个字符,预计需要花费 5 分钟才能阅读完成。

本文次要钻研一下 dubbo-go 的 randomLoadBalance

randomLoadBalance

dubbo-go-v1.4.2/cluster/loadbalance/random.go

const (name = "random")

func init() {extension.SetLoadbalance(name, NewRandomLoadBalance)
}

type randomLoadBalance struct {
}

// NewRandomLoadBalance ...
func NewRandomLoadBalance() cluster.LoadBalance {return &randomLoadBalance{}
}
  • randomLoadBalance 的 NewRandomLoadBalance 办法创立 randomLoadBalance

Select

dubbo-go-v1.4.2/cluster/loadbalance/random.go

func (lb *randomLoadBalance) Select(invokers []protocol.Invoker, invocation protocol.Invocation) protocol.Invoker {
    var length int
    if length = len(invokers); length == 1 {return invokers[0]
    }
    sameWeight := true
    weights := make([]int64, length)

    firstWeight := GetWeight(invokers[0], invocation)
    totalWeight := firstWeight
    weights[0] = firstWeight

    for i := 1; i < length; i++ {weight := GetWeight(invokers[i], invocation)
        weights[i] = weight

        totalWeight += weight
        if sameWeight && weight != firstWeight {sameWeight = false}
    }

    if totalWeight > 0 && !sameWeight {// If (not every invoker has the same weight & at least one invoker's weight>0), select randomly based on totalWeight.
        offset := rand.Int63n(totalWeight)

        for i := 0; i < length; i++ {offset -= weights[i]
            if offset < 0 {return invokers[i]
            }
        }
    }
    // If all invokers have the same weight value or totalWeight=0, return evenly.
    return invokers[rand.Intn(length)]
}
  • Select 办法先判断 invokers 数量,若只有一个则返回 invokers[0];之后遍历 invokers 计算 totalWeight 及 sameWeight,若 totalWeight 大于 0 且 sameWeight 为 false 则应用 rand.Int63n(totalWeight) 随机一个 offset,之后遍历 weights,用 offset 挨个去减 weights[i],若 offset 小于 0,则返回 invokers[i];若都没有选中,则返回 invokers[rand.Intn(length)]

小结

randomLoadBalance 的 NewRandomLoadBalance 办法创立 randomLoadBalance;其 Select 办法应用了带 weight 的办法,具体就是应用 rand.Int63n(totalWeight) 随机一个 offset,之后遍历 weights,用 offset 挨个去减 weights[i],若 offset 小于 0,则返回 invokers[i]

doc

  • random
正文完
 0