-
Notifications
You must be signed in to change notification settings - Fork 4
/
Dispatch.go
95 lines (74 loc) · 1.96 KB
/
Dispatch.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package main
import (
"fmt"
"math/rand"
"net"
"strings"
"time"
)
func getBackendHost(sAddr net.Addr) (string, bool) {
lock.RLock()
defer lock.RUnlock()
sIP := strings.Split(sAddr.String(), ":")[0]
IP := net.ParseIP(sIP).To4()
nIP := int(IP[0]) + int(IP[1])*255 + int(IP[2])*255*255 + int(IP[3])*255*255*255
hash := nIP % 1000
fmt.Printf("sIP=%s, nIP=%d, hash=%d\n", sIP, nIP, hash)
for _, group := range ALLHOST.AllHost {
if hash >= group.Min && hash <= group.Max {
if ALLHOST.Mode == "master" { //优选主,如果主不可用则选从
for _, host := range group.Hosts {
if host.Status == 0 {
return host.IP, true
}
}
} else if ALLHOST.Mode == "hash" { //优选hash对应的,如果hash分配的不可用, 用随机分配
hostNum := len(group.Hosts)
r := hash % hostNum
if group.Hosts[r].Status == 0 {
return group.Hosts[r].IP, true
} else { //如果hash分配的不可用, 用随机分配
for l := 0; l < hostNum*2; l++ {
r := rand.Intn(hostNum)
if group.Hosts[r].Status == 0 {
return group.Hosts[r].IP, true
}
}
}
} else if ALLHOST.Mode == "rand" {
hostNum := len(group.Hosts)
for l := 0; l < hostNum*2; l++ {
r := rand.Intn(hostNum)
if group.Hosts[r].Status == 0 {
return group.Hosts[r].IP, true
}
}
}
}
}
return "", false
}
func CheckHosts() {
for {
LoadConfig() //加载配置文件
for i, group := range ALLHOST.AllHost {
for ii, host := range group.Hosts {
conn, err := net.DialTimeout("tcp", host.IP, 2*time.Second)
if err != nil {
lock.Lock()
ALLHOST.AllHost[i].Hosts[ii].Status -= 1
lock.Unlock()
} else if host.Status != 0 {
lock.Lock()
ALLHOST.AllHost[i].Hosts[ii].Status = 0
lock.Unlock()
}
if err == nil {
conn.Close()
}
}
}
fmt.Printf("\nCheckHosts AllHost: %+v\n", ALLHOST)
time.Sleep(time.Duration(ALLHOST.CheckInterval) * time.Second)
}
}