-
Notifications
You must be signed in to change notification settings - Fork 0
/
balancer.go
48 lines (41 loc) · 992 Bytes
/
balancer.go
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
44
45
46
47
48
package balancer
import "sync"
//Balancer select a node to send load
type Balancer struct {
UpstreamPool []Node
load uint64
Policy SelectionPolicy
m *sync.RWMutex
}
//NewBalancer create a new balancer with default properties
func NewBalancer() *Balancer {
return &Balancer{
UpstreamPool: make([]Node, 0),
load: 0,
Policy: &RoundRobin{},
m: &sync.RWMutex{},
}
}
//Add add a node to balancer
func (b *Balancer) Add(node ...Node) {
b.UpstreamPool = append(b.UpstreamPool, node...)
}
//Remove remove a node from balancer
func (b *Balancer) Remove(nodeID string) {
b.m.Lock()
defer b.m.Unlock()
i := 0
for _, upstream := range b.UpstreamPool {
if upstream.NodeID() != nodeID {
b.UpstreamPool[i] = upstream
i++
}
}
b.UpstreamPool = b.UpstreamPool[:i]
}
//Next select next available node
func (b *Balancer) Next(clientID string) Node {
defer b.m.Unlock()
b.m.Lock()
return b.Policy.SelectNode(b, clientID)
}