-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhash.go
39 lines (33 loc) · 754 Bytes
/
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
package balancer
import (
"github.com/fufuok/load-balancer/internal/doublejump"
"github.com/fufuok/load-balancer/utils"
)
// JumpConsistentHash
type consistentHash struct {
count int
h *doublejump.Hash
}
func NewConsistentHash(choices ...*Choice) (lb *consistentHash) {
lb = &consistentHash{}
lb.Update(choices)
return
}
func (b *consistentHash) Select(key ...string) (item interface{}) {
if b.count == 0 {
return
}
hash := utils.HashString(key...)
return b.h.Get(hash).(*Choice).Item
}
func (b *consistentHash) Name() string {
return "ConsistentHash"
}
func (b *consistentHash) Update(choices []*Choice) bool {
b.count = len(choices)
b.h = doublejump.NewHash()
for i := range choices {
b.h.Add(choices[i])
}
return true
}