Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: RandomLoadBalance code optimization #1899

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 13 additions & 10 deletions cluster/loadbalance/random/loadbalance.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,23 +42,27 @@ func NewRandomLoadBalance() loadbalance.LoadBalance {
}

func (lb *randomLoadBalance) Select(invokers []protocol.Invoker, invocation protocol.Invocation) protocol.Invoker {

// Number of invokers
var length int
if length = len(invokers); length == 1 {
return invokers[0]
}

// Every invoker has the same weight?
sameWeight := true
// the maxWeight of every invokers, the minWeight = 0 or the maxWeight of the last invoker
weights := make([]int64, length)
// The sum of weights
var totalWeight int64 = 0

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

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

//Sum
totalWeight += weight
if sameWeight && weight != firstWeight {
// save for later use
weights[i] = totalWeight
if sameWeight && totalWeight != weight*(int64(i+1)) {
sameWeight = false
}
}
Expand All @@ -68,8 +72,7 @@ func (lb *randomLoadBalance) Select(invokers []protocol.Invoker, invocation prot
offset := rand.Int63n(totalWeight)

for i := 0; i < length; i++ {
offset -= weights[i]
if offset < 0 {
if offset < weights[i] {
return invokers[i]
}
}
Expand Down