Repository navigation
Expand file tree
/
Copy pathbalancer.go
More file actions
executable file
·79 lines (69 loc) · 1.7 KB
/
Copy pathbalancer.go
File metadata and controls
executable file
·79 lines (69 loc) · 1.7 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
package main
import (
"math/rand"
"net"
"time"
"stathat.com/c/consistent"
)
// 代理服务的结构
type BackendSvr struct {
identify string
isLive bool // 服务是否存活
failTimes int
}
var (
Consisthash *consistent.Consistent
BackendSvrs map[string]*BackendSvr
)
// 初始化代理服务,加入一致性哈希列表,开始检测服务
func initBackendSvrs(serverList []string) {
Consisthash = consistent.New()
BackendSvrs = make(map[string]*BackendSvr)
for _, server := range serverList {
Consisthash.Add(server)
BackendSvrs[server] = &BackendSvr{
identify: server,
isLive: true,
failTimes: 0,
}
}
go checkBackendSvrs()
}
// 根据客户端链接,从哈希集群中选择一台机器
func getBackendSvr(conn net.Conn) (*BackendSvr, bool) {
remoteAddr := conn.RemoteAddr().String()
identify, _ := Consisthash.Get(remoteAddr)
BackendSvr, ok := BackendSvrs[identify]
return BackendSvr, ok
}
// 代理服务检测存活
func checkBackendSvrs() {
rand.Seed(time.Now().UnixNano())
// 设置定时(10s对服务进行检测)执行管道
ticker := time.Tick(time.Duration(10) * time.Second)
for _ = range ticker {
for _, server := range BackendSvrs {
if server.failTimes >= Config.FailOver && server.isLive == true {
server.isLive = false
Consisthash.Remove(server.identify)
}
}
}
}
// 设置定时器
func timer(input chan interface{}) {
timerOne := time.NewTimer(time.Second * 5)
timerTwo := time.NewTimer(time.Second * 10)
for {
select {
case msg := <-input:
println(msg)
case <-timerOne.C:
println("5s timer")
timerOne.Reset(time.Second * 5)
case <-timerTwo.C:
println("10s timer")
timerTwo.Reset(time.Second * 10)
}
}
}