-
Notifications
You must be signed in to change notification settings - Fork 0
/
wrr.go
85 lines (69 loc) · 1.29 KB
/
wrr.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
package wrr
import "sync"
type Balancer struct {
sync.RWMutex
list map[string]*Item
}
type Item struct {
key string
weight Weight
}
type Weight struct {
init int
current int
effective int
}
func Init() *Balancer {
b := &Balancer{}
b.list = make(map[string]*Item)
return b
}
func (b *Balancer) Add(key string, weight int) {
b.Lock()
defer b.Unlock()
b.list[key] = &Item{
key: key,
weight: Weight{init: weight, effective: weight},
}
}
func (b *Balancer) Next() string {
b.Lock()
defer b.Unlock()
if len(b.list) == 0 {
return ""
}
var total int
var best *Item
for _, item := range b.list {
total += item.weight.effective
item.weight.current += item.weight.effective
if best == nil || item.weight.current > best.weight.current {
best = item
}
}
best.weight.current -= total
return best.key
}
func (b *Balancer) Remove(key string) {
b.Lock()
defer b.Unlock()
delete(b.list, key)
}
func (b *Balancer) IncWeight(key string) {
b.Lock()
defer b.Unlock()
item := b.list[key]
if item == nil || item.weight.effective >= item.weight.init {
return
}
item.weight.effective++
}
func (b *Balancer) DecWeight(key string) {
b.Lock()
defer b.Unlock()
item := b.list[key]
if item == nil || item.weight.effective <= 0 {
return
}
item.weight.effective--
}