-
Notifications
You must be signed in to change notification settings - Fork 0
/
balancer.go
69 lines (60 loc) · 1.23 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
package toxy
import (
"log"
"math/rand"
)
type Balancer struct {
services []*ResolverService
state []int
balancerType string
}
func NewBalancer(services []*ResolverService, balancerType string) *Balancer {
b := &Balancer{
services: services,
state: []int{},
balancerType: balancerType,
}
return b
}
func (b *Balancer) random() *ResolverService {
return b.services[rand.Intn(len(b.services)-0)+0]
}
func (b *Balancer) initSequential() {
for k := range b.services {
b.state = append(b.state, k)
}
}
func (b *Balancer) sequential() *ResolverService {
for k := range b.state {
if k+1 < len(b.state) {
if b.state[k] < b.state[k+1] {
b.state[k]++
if b.services[k].State != ServiceUp {
continue
}
return b.services[k]
}
} else {
b.state[k]++
return b.services[k]
}
}
return nil
}
func (b *Balancer) getServiceAt(index int) *ResolverService {
return b.services[index]
}
func (b *Balancer) selectService() *ResolverService {
switch b.balancerType {
case Random:
return b.random()
case Sequential:
return b.sequential()
default:
return b.getServiceAt(0)
}
}
func (b *Balancer) getCurrentState() {
log.Printf("%+v \n", b.state)
log.Printf("%+v \n", b.services)
}