-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathcluster.go
58 lines (51 loc) · 1.19 KB
/
cluster.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
package client
import (
"errors"
"hash/crc32"
"time"
)
type Partition struct {
Id int
Master string
Slaves []string
}
type cluster struct {
clients map[int]*Client
}
func NewCluster(partitions []*Partition, timeout time.Duration) (*cluster, error) {
if len(partitions) <= 0 {
return nil, errors.New("partitions is required non empty")
}
clients := make(map[int]*Client)
for _, p := range partitions {
var c *Client
var err error
if len(p.Slaves) <= 0 {
c, err = New(p.Master, timeout)
} else {
c, err = NewMS(p.Master, p.Slaves, timeout)
}
if err != nil {
return nil, err
}
clients[p.Id] = c
}
return &cluster{
clients: clients,
}, nil
}
func (c *cluster) Get(key string) (*Result, error) {
size := len(c.clients)
hash := (int)(crc32.ChecksumIEEE([]byte(key)))
return c.clients[hash%size].Get(key)
}
func (c *cluster) Put(key string, value string) (*Result, error) {
size := len(c.clients)
hash := (int)(crc32.ChecksumIEEE([]byte(key)))
return c.clients[hash%size].Put(key, value)
}
func (c *cluster) Delete(key string) (*Result, error) {
size := len(c.clients)
hash := (int)(crc32.ChecksumIEEE([]byte(key)))
return c.clients[hash%size].Delete(key)
}