reverseproxy: Optimize base case for least_conn and random_choose policies (#5487)

When only a single request has the least amount of requests, there's no need to compute a random number, because the modulo of 1 will always be 0 anyways.
This commit is contained in:
Francis Lavoie 2023-05-05 22:53:48 -04:00 committed by GitHub
parent 335cd2e8a4
commit b19946f6af
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -187,7 +187,7 @@ func (LeastConnSelection) Select(pool UpstreamPool, _ *http.Request, _ http.Resp
// sample: https://en.wikipedia.org/wiki/Reservoir_sampling // sample: https://en.wikipedia.org/wiki/Reservoir_sampling
if numReqs == leastReqs { if numReqs == leastReqs {
count++ count++
if (weakrand.Int() % count) == 0 { //nolint:gosec if count > 1 || (weakrand.Int()%count) == 0 { //nolint:gosec
bestHost = host bestHost = host
} }
} }
@ -707,6 +707,9 @@ func leastRequests(upstreams []*Upstream) *Upstream {
if len(best) == 0 { if len(best) == 0 {
return nil return nil
} }
if len(best) == 1 {
return best[0]
}
return best[weakrand.Intn(len(best))] //nolint:gosec return best[weakrand.Intn(len(best))] //nolint:gosec
} }