-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathstrategy_roundrobin.go
More file actions
56 lines (49 loc) · 1.31 KB
/
Copy pathstrategy_roundrobin.go
File metadata and controls
56 lines (49 loc) · 1.31 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
44
45
46
47
48
49
50
51
52
53
54
55
56
package cslb
import (
"errors"
"math"
"math/rand"
"sync/atomic"
"unsafe"
)
type roundRobinStrategy struct {
index uint64
internalNodes unsafe.Pointer // pointer to roundRobinInternalNodes
}
type roundRobinInternalNodes struct {
nodes []Node
order []int
}
func NewRoundRobinStrategy() *roundRobinStrategy {
return &roundRobinStrategy{
index: math.MaxUint64,
internalNodes: nil,
}
}
func (s *roundRobinStrategy) SetNodes(nodes []Node) {
internalNodes := &roundRobinInternalNodes{
nodes: nodes,
order: make([]int, len(nodes)),
}
for i := 0; i < len(internalNodes.order); i++ {
internalNodes.order[i] = i
}
rand.Shuffle(len(internalNodes.order), func(i, j int) {
internalNodes.order[i], internalNodes.order[j] = internalNodes.order[j], internalNodes.order[i]
})
atomic.StorePointer(&s.internalNodes, unsafe.Pointer(internalNodes))
}
func (s *roundRobinStrategy) Next() (Node, error) {
internalNodes := (*roundRobinInternalNodes)(atomic.LoadPointer(&s.internalNodes))
nodes := internalNodes.nodes
order := internalNodes.order
if len(nodes) > 0 {
index := atomic.AddUint64(&s.index, 1) % uint64(len(order))
return nodes[order[index]], nil
} else {
return nil, errors.New("empty node list")
}
}
func (s *roundRobinStrategy) NextFor(interface{}) (Node, error) {
return s.Next()
}