-
Notifications
You must be signed in to change notification settings - Fork 0
/
balancer.go
65 lines (51 loc) · 1.1 KB
/
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package call
type ReplicaConnection interface {
Address() string
}
type Balancer interface {
Add(ReplicaConnection)
Remove(ReplicaConnection)
Pick(CallOptions) (ReplicaConnection, bool)
}
func RoundRobin() Balancer {
return &roundRobin{}
}
type roundRobin struct {
connList
next int
}
var _ Balancer = &roundRobin{}
func (rr *roundRobin) Add(connection ReplicaConnection) {
rr.connList.Add(connection)
}
func (rr *roundRobin) Remove(connection ReplicaConnection) {
rr.connList.Remove(connection)
}
func (rr *roundRobin) Pick(options CallOptions) (ReplicaConnection, bool) {
if len(rr.list) == 0 {
return nil, false
}
if rr.next >= len(rr.list) {
rr.next = 0
}
c := rr.list[rr.next]
rr.next += 1
return c, true
}
// connList
type connList struct {
list []ReplicaConnection
}
func (cl *connList) Add(connection ReplicaConnection) {
cl.list = append(cl.list, connection)
}
func (cl *connList) Remove(connection ReplicaConnection) {
for i, c := range cl.list {
if c != connection {
continue
}
cl.list[i] = cl.list[len(cl.list)-1]
cl.list = cl.list[:len(cl.list)-1]
return
}
}