-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconsistent_hash.go
62 lines (51 loc) · 1.13 KB
/
consistent_hash.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
package sipnexus
import (
"fmt"
"hash/fnv"
"sort"
"sync"
)
type ConsistentHash struct {
circle map[uint32]string
sortedHashes []uint32
virtualNodes int
mu sync.RWMutex
}
func NewConsistentHash(virtualNodes int) *ConsistentHash {
return &ConsistentHash{
circle: make(map[uint32]string),
virtualNodes: virtualNodes,
}
}
func (c *ConsistentHash) Add(node string) {
c.mu.Lock()
defer c.mu.Unlock()
for i := 0; i < c.virtualNodes; i++ {
hash := c.hash(fmt.Sprintf("%s:%d", node, i))
c.circle[hash] = node
c.sortedHashes = append(c.sortedHashes, hash)
}
sort.Slice(c.sortedHashes, func(i, j int) bool {
return c.sortedHashes[i] < c.sortedHashes[j]
})
}
func (c *ConsistentHash) Get(key string) string {
c.mu.RLock()
defer c.mu.RUnlock()
if len(c.circle) == 0 {
return ""
}
hash := c.hash(key)
idx := sort.Search(len(c.sortedHashes), func(i int) bool {
return c.sortedHashes[i] >= hash
})
if idx == len(c.sortedHashes) {
idx = 0
}
return c.circle[c.sortedHashes[idx]]
}
func (c *ConsistentHash) hash(key string) uint32 {
h := fnv.New32a()
h.Write([]byte(key))
return h.Sum32()
}