-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworker_loadblance.go
More file actions
109 lines (91 loc) · 2.1 KB
/
worker_loadblance.go
File metadata and controls
109 lines (91 loc) · 2.1 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
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
100
101
102
103
104
105
106
107
108
109
package smart
import (
"gitee.com/ywengineer/smart-kit/pkg/logk"
"github.com/bytedance/gopkg/lang/fastrand"
"go.uber.org/zap"
"sync/atomic"
)
// LoadBalance sets the load balancing method.
type LoadBalance int
const (
// Random requests that connections are randomly distributed.
Random LoadBalance = iota
// Hash requests that connections are bind to a fixed pool.
Hash
RoundRobin
)
// loadBalance sets the load balancing method for []*Pool
type loadBalance interface {
LoadBalance() LoadBalance
// Pick Choose the most qualified Pool
Pick(id int) Worker
}
func parseLoadBalance(lb string) LoadBalance {
switch lb {
case "random":
return Random
case "hash":
return Hash
case "rr":
return RoundRobin
}
logk.Warn("unknown load balance, default to RoundRobin", zap.String("lb", lb))
return RoundRobin
}
func newLoadBalance(lb LoadBalance, pools []Worker) loadBalance {
switch lb {
case Random:
return newRandomLB(pools)
case Hash:
return newHashLB(pools)
case RoundRobin:
return newRoundRobinLB(pools)
}
return newRoundRobinLB(pools)
}
// randomLB
func newRandomLB(pools []Worker) loadBalance {
return &randomLB{pools: pools, poolSize: len(pools)}
}
type randomLB struct {
pools []Worker
poolSize int
}
func (b *randomLB) LoadBalance() LoadBalance {
return Random
}
func (b *randomLB) Pick(id int) Worker {
idx := fastrand.Intn(b.poolSize)
return b.pools[idx]
}
// hashLB
func newHashLB(pools []Worker) loadBalance {
return &hashLB{pools: pools, poolSize: len(pools)}
}
type hashLB struct {
pools []Worker
poolSize int
}
func (b *hashLB) LoadBalance() LoadBalance {
return Hash
}
func (b *hashLB) Pick(id int) Worker {
idx := id % b.poolSize
return b.pools[idx]
}
// roundRobinLB
func newRoundRobinLB(pools []Worker) loadBalance {
return &roundRobinLB{pools: pools, poolSize: len(pools)}
}
type roundRobinLB struct {
pools []Worker
accepted uintptr // accept counter
poolSize int
}
func (b *roundRobinLB) LoadBalance() LoadBalance {
return Hash
}
func (b *roundRobinLB) Pick(id int) Worker {
idx := int(atomic.AddUintptr(&b.accepted, 1)) % b.poolSize
return b.pools[idx]
}