/
weight_round_strategy.go
79 lines (70 loc) · 1.61 KB
/
weight_round_strategy.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
package load_balance
import (
"errors"
"strconv"
)
type WeightRoundRobinStrategy struct {
curIndex int
rss []*WeightNode
rsw []int
conf LoadBalanceConf
}
type WeightNode struct {
addr string
weight int //权重值
currentWeight int //节点当前权重
effectiveWeight int //有效权重
}
func (r *WeightRoundRobinStrategy) Add(params ...string) error {
if len(params) != 2 {
return errors.New("param len need 2")
}
parInt, err := strconv.ParseInt(params[1], 10, 64)
if err != nil {
return err
}
node := &WeightNode{addr: params[0], weight: int(parInt)}
node.effectiveWeight = node.weight
r.rss = append(r.rss, node)
return nil
}
func (r *WeightRoundRobinStrategy) Next() string {
total := 0
var best *WeightNode
for i := 0; i < len(r.rss); i++ {
w := r.rss[i]
total += w.effectiveWeight
w.currentWeight += w.effectiveWeight
if w.effectiveWeight < w.weight {
w.effectiveWeight++
}
if best == nil || w.currentWeight > best.currentWeight {
best = w
}
}
if best == nil {
return ""
}
best.currentWeight -= total
return best.addr
}
func (r *WeightRoundRobinStrategy) Get(key string) (string, error) {
return r.Next(), nil
}
func (r *WeightRoundRobinStrategy) GetAll() ([]string, error) {
iplist := []string{}
for _, item := range r.rss {
iplist = append(iplist, item.addr)
}
return iplist, nil
}
func (r *WeightRoundRobinStrategy) RemoveAll() error {
r.rss = []*WeightNode{}
r.rsw = []int{}
return nil
}
func init() {
RegisterLoadBalanceStrategyHandler("weight_round", func() LoadBalanceStrategy {
return &WeightRoundRobinStrategy{}
})
}