本文主要研究一下dubbo-go的randomLoadBalancedom
dubbo-go-v1.4.2/cluster/loadbalance/random.gocode
const ( name = "random" ) func init() { extension.SetLoadbalance(name, NewRandomLoadBalance) } type randomLoadBalance struct { } // NewRandomLoadBalance ... func NewRandomLoadBalance() cluster.LoadBalance { return &randomLoadBalance{} }
dubbo-go-v1.4.2/cluster/loadbalance/random.goit
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)] }
randomLoadBalance的NewRandomLoadBalance方法建立randomLoadBalance;其Select方法使用了帶weight的方法,具體就是使用rand.Int63n(totalWeight)隨機一個offset,以後遍歷weights,用offset挨個去減weights[i],若offset小於0,則返回invokers[i]io