-
Notifications
You must be signed in to change notification settings - Fork 63
/
balancer.go
62 lines (51 loc) · 1.14 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
// Author: zheng-ji.info
package main
import (
//"fmt"
"math/rand"
"net"
"stathat.com/c/consistent"
"time"
)
// BackendSvr Type
type BackendSvr struct {
svrStr string
isUp bool // is Up or Down
failTimes int
}
var (
pConsisthash *consistent.Consistent
pBackendSvrs map[string]*BackendSvr
)
func initBackendSvrs(svrs []string) {
pConsisthash = consistent.New()
pBackendSvrs = make(map[string]*BackendSvr)
for _, svr := range svrs {
pConsisthash.Add(svr)
pBackendSvrs[svr] = &BackendSvr{
svrStr: svr,
isUp: true,
failTimes: 0,
}
}
go checkBackendSvrs()
}
func getBackendSvr(conn net.Conn) (*BackendSvr, bool) {
remoteAddr := conn.RemoteAddr().String()
svr, _ := pConsisthash.Get(remoteAddr)
bksvr, ok := pBackendSvrs[svr]
return bksvr, ok
}
func checkBackendSvrs() {
// scheduler every 10 seconds
rand.Seed(time.Now().UnixNano())
t := time.Tick(time.Duration(10)*time.Second + time.Duration(rand.Intn(100))*time.Millisecond*100)
for _ = range t {
for _, v := range pBackendSvrs {
if v.failTimes >= pConfig.FailOver && v.isUp == true {
v.isUp = false
pConsisthash.Remove(v.svrStr)
}
}
}
}