本文主要研究一下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


codecraft
11.9k 声望2k 粉丝

当一个代码的工匠回首往事时,不因虚度年华而悔恨,也不因碌碌无为而羞愧,这样,当他老的时候,可以很自豪告诉世人,我曾经将代码注入生命去打造互联网的浪潮之巅,那是个很疯狂的时代,我在一波波的浪潮上留下...


引用和评论

0 条评论