forked from larkwins/x
-
Notifications
You must be signed in to change notification settings - Fork 0
/
consistent.go
105 lines (84 loc) · 1.81 KB
/
consistent.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
96
97
98
99
100
101
102
103
104
105
package consistent
import (
"encoding/json"
"fmt"
"sync"
//"stathat.com/c/consistent"
consistent "github.com/huichen/consistent_hashing"
)
var redis_nodes = []string{
"192.168.99.106:7000",
"192.168.99.157:7000",
"192.168.99.157:7001",
"192.168.99.153:7001",
"192.168.99.153:7002",
"192.168.99.153:7003",
"192.168.99.153:7004",
}
var keys = []string{
"gd", "hn",
}
func main() {
ring := NewHashRing(redis_nodes, 0)
m := map[string][]string{}
for _, node := range redis_nodes {
m[node] = []string{}
}
for _, p := range keys {
node, _ := ring.GetNode(p)
// fmt.Println(p, "->", node)
m[node] = append(m[node], p)
}
fmt.Println(m)
}
type HashRing struct {
sync.RWMutex
ring *consistent.Consistent
stats map[string]*Stat
}
type Stat struct {
sync.RWMutex
TotalHit int
KeyHit map[string]int
}
func (s Stat) String() string {
bytes, _ := json.Marshal(&s)
return string(bytes)
}
func NewHashRing(nodes []string, numberOfReplicas ...int) *HashRing {
ret := &HashRing{
ring: consistent.New(),
stats: make(map[string]*Stat),
}
if len(numberOfReplicas) > 0 && numberOfReplicas[0] > 0 {
ret.SetNumberOfReplicas(numberOfReplicas[0])
}
ret.SetNodes(nodes)
return ret
}
func (this *HashRing) SetNodes(nodes []string) {
for _, node := range nodes {
this.ring.Add(node)
this.stats[node] = &Stat{KeyHit: make(map[string]int)}
}
}
func (this *HashRing) SetNumberOfReplicas(num int) {
this.ring.NumberOfReplicas = num
}
func (this HashRing) GetNode(pk string) (string, error) {
node, err := this.ring.Get(pk)
go this.hit(node, pk)
return node, err
}
func (this *HashRing) hit(node, key string) {
this.RLock()
stat := this.stats[node]
this.RUnlock()
stat.Lock()
stat.TotalHit++
stat.KeyHit[key]++
stat.Unlock()
}
func (this HashRing) Stats() map[string]*Stat {
return this.stats
}