/
goRoundRobin.go
78 lines (65 loc) · 1.38 KB
/
goRoundRobin.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
//++++++++++++++++++++++++++++++++++++++++
// 《Go语言高级开发与实战》源码
//++++++++++++++++++++++++++++++++++++++++
// Author:廖显东(ShirDon)
// Blog:https://www.shirdon.com/
// 知乎:https://www.zhihu.com/people/shirdonl
// 公众号:源码大数据
// 仓库地址:https://gitee.com/shirdonl/goAdvanced
// 仓库地址:https://github.com/shirdonl/goAdvanced
//++++++++++++++++++++++++++++++++++++++++
package main
import (
"errors"
"fmt"
"sync"
)
var (
//没有可用项
ErrNoAvailableItem = errors.New("没有可用项")
)
// 轮询负载均衡器实例
type RoundRobinBalancer struct {
m sync.Mutex
next int
items []interface{}
}
// 实例化负载均衡器
func New(items []interface{}) *RoundRobinBalancer {
return &RoundRobinBalancer{items: items}
}
// 选择可用项
func (b *RoundRobinBalancer) Pick() (interface{}, error) {
if len(b.items) == 0 {
return nil, ErrNoAvailableItem
}
b.m.Lock()
r := b.items[b.next]
b.next = (b.next + 1) % len(b.items)
b.m.Unlock()
return r, nil
}
func main() {
source := []interface{}{"10.0.0.1", "10.0.0.2", "10.0.0.3"}
b := New(source)
wc := sync.WaitGroup{}
for i := 0; i < 2; i++ {
wc.Add(1)
go func() {
v, _ := b.Pick()
fmt.Printf("%v\n", v.(string))
wc.Done()
}()
}
wc.Wait()
}
//10.0.0.2
//10.0.0.1
//10.0.0.2
//10.0.0.3
//10.0.0.1
//10.0.0.2
//10.0.0.3
//10.0.0.1
//10.0.0.3
//10.0.0.1