sequence
This article mainly studies dubo-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{}
}
Copy the code
- RandomLoadBalance the NewRandomLoadBalance method creates 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)] }Copy the code
- Select invokers[0]; Select invokers[0]; If the totalWeight is greater than 0 and sameWeight is false, use rand.Int63n(totalWeight) to calculate the totalWeight and sameWeight. Subtract weights[I] one by one with offset, if offset is less than 0, return invokers[I]; If none is selected, return invokers[rand.Intn(length)]
summary
RandomLoadBalance’s NewRandomLoadBalance method creates randomLoadBalance; Int63n(totalWeight) Select weights from rate.int63n (totalWeight) at random, then go through weights one by one to subtract weights[I]. If offset is less than 0, It returns invokers [I]
doc
- random