-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathalgorithm.go
More file actions
43 lines (35 loc) · 1.07 KB
/
Copy pathalgorithm.go
File metadata and controls
43 lines (35 loc) · 1.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package main
import (
"math"
"sync/atomic"
)
var rrCounter uint64
func LeastConnections(servers []*Server) *Server {
if len(servers) == 0 {
return nil
}
var bestServers []*Server
var bestScore float64 = math.MaxFloat64
// If a server has the same number of connections, we prefer the one with the less weight
// If both the connections and the weights are same then we waana RoundRobin
for _, server := range servers {
serverCon := atomic.LoadInt64(&server.Connections) // Thread Safe Read as traffic in Go is crazy fast
serverWeight := atomic.LoadInt64(&server.Weight)
if serverWeight <= 0 {
serverWeight = 1 // Guard against an Invalid config
}
// Lower score = Less loaded relative to its capacity
score := float64(serverCon) / float64(serverWeight)
if score < bestScore {
bestScore = score
bestServers = []*Server{server}
} else if score == bestScore {
bestServers = append(bestServers, server)
}
}
if len(bestServers) == 0 {
return nil
}
idx := atomic.AddUint64(&rrCounter, 1)
return bestServers[idx % uint64(len(bestServers))]
}