forked from buraksezer/consistent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sample.go
53 lines (43 loc) · 1.34 KB
/
sample.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
package main
import (
"fmt"
"github.com/buraksezer/consistent"
"github.com/cespare/xxhash"
)
// In your distributed system, you probably have a custom data type
// for your cluster members. Just add a String function to implement
// consistent.Member interface.
type myMember string
func (m myMember) String() string {
return string(m)
}
// consistent package doesn't provide a default hashing function.
// You should provide a proper one to distribute keys/members uniformly.
type hasher struct{}
func (h hasher) Sum64(data []byte) uint64 {
// you should use a proper hash function for uniformity.
return xxhash.Sum64(data)
}
func main() {
// Create a new consistent instance
cfg := consistent.Config{
PartitionCount: 7,
ReplicationFactor: 20,
Load: 1.25,
Hasher: hasher{},
}
c := consistent.New(nil, cfg)
// Add some members to the consistent hash table.
// Add function calculates average load and distributes partitions over members
node1 := myMember("node1.olricmq.com")
c.Add(node1)
node2 := myMember("node2.olricmq.com")
c.Add(node2)
key := []byte("my-key")
// calculates partition id for the given key
// partID := hash(key) % partitionCount
// the partitions is already distributed among members by Add function.
owner := c.LocateKey(key)
fmt.Println(owner.String())
// Prints node2.olricmq.com
}