-
Notifications
You must be signed in to change notification settings - Fork 8
/
balancer.go
99 lines (78 loc) · 1.89 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package rpc
import (
"math/rand"
"strings"
"sync/atomic"
"github.com/cuigh/auxo/data"
)
// todo: move to balancer pkg
var balancers = map[string]BalancerBuilder{}
func init() {
RegisterBalancer(randomBalancerBuilder{})
RegisterBalancer(roundRobinBalancerBuilder{})
}
func RegisterBalancer(b BalancerBuilder) {
balancers[strings.ToLower(b.Name())] = b
}
func GetBalancer(name string) BalancerBuilder {
return balancers[strings.ToLower(name)]
}
// BalancerBuilder creates a balancer.
type BalancerBuilder interface {
// Name returns the name of balancers built by this builder.
// It will be used to pick balancers (for example in service config).
Name() string
// Build creates a new balancer with the options.
Build(opts data.Map) Balancer
}
type BalancerOptions struct {
}
type Balancer interface {
Update(nodes []*Node)
Next() (*Node, error)
}
type randomBalancerBuilder struct {
}
func (randomBalancerBuilder) Name() string {
return "random"
}
func (randomBalancerBuilder) Build(opts data.Map) Balancer {
return new(randomBalancer)
}
type randomBalancer struct {
nodes []*Node
}
func (b *randomBalancer) Update(nodes []*Node) {
b.nodes = nodes
}
func (b *randomBalancer) Next() (*Node, error) {
nodes := b.nodes
if l := len(nodes); l > 0 {
return nodes[rand.Intn(l)], nil
}
return nil, ErrNodeUnavailable
}
type roundRobinBalancerBuilder struct {
}
func (roundRobinBalancerBuilder) Name() string {
return "round_robin"
}
func (roundRobinBalancerBuilder) Build(opts data.Map) Balancer {
return new(roundRobinBalancer)
}
type roundRobinBalancer struct {
nodes []*Node
counter int64
}
func (b *roundRobinBalancer) Update(nodes []*Node) {
b.counter = -1
b.nodes = nodes
}
func (b *roundRobinBalancer) Next() (*Node, error) {
nodes := b.nodes
if l := len(nodes); l > 0 {
i := atomic.AddInt64(&b.counter, 1) % int64(l)
return nodes[i], nil
}
return nil, ErrNodeUnavailable
}