-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
ring.go
50 lines (40 loc) · 971 Bytes
/
ring.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
package backend
import (
"sync"
"github.com/toolkits/pkg/consistent"
)
type ConsistentHashRing struct {
sync.RWMutex
ring *consistent.Consistent
}
func (c *ConsistentHashRing) GetNode(pk string) (string, error) {
c.RLock()
defer c.RUnlock()
return c.ring.Get(pk)
}
func (c *ConsistentHashRing) Set(r *consistent.Consistent) {
c.Lock()
defer c.Unlock()
c.ring = r
}
func (c *ConsistentHashRing) GetRing() *consistent.Consistent {
c.RLock()
defer c.RUnlock()
return c.ring
}
func NewConsistentHashRing(replicas int32, nodes []string) *ConsistentHashRing {
ret := &ConsistentHashRing{ring: consistent.New()}
ret.ring.NumberOfReplicas = int(replicas)
for i := 0; i < len(nodes); i++ {
ret.ring.Add(nodes[i])
}
return ret
}
func RebuildConsistentHashRing(hashRing *ConsistentHashRing, nodes []string, replicas int) {
r := consistent.New()
r.NumberOfReplicas = replicas
for i := 0; i < len(nodes); i++ {
r.Add(nodes[i])
}
hashRing.Set(r)
}