-
Notifications
You must be signed in to change notification settings - Fork 0
/
ip_hash.go
62 lines (50 loc) · 1.06 KB
/
ip_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 iphash
import (
"errors"
"net/url"
"sync"
"unsafe"
"github.com/cespare/xxhash"
"github.com/hlts2/round-robin"
)
// ErrServersNotExists is the error that servers dose not exists
var ErrServersNotExists = errors.New("servers dose not exist")
// IPHash is base ip-hash interface
type IPHash interface {
Next(in *url.URL) *url.URL
}
type iphash struct {
urls []*url.URL
cnt uint64
m map[uint64]*url.URL
mu *sync.RWMutex
rr roundrobin.RoundRobin
}
// New returns IPHash(*iphash) object
func New(urls []*url.URL) (IPHash, error) {
if len(urls) == 0 {
return nil, ErrServersNotExists
}
rr, _ := roundrobin.New(urls)
return &iphash{
urls: urls,
cnt: uint64(len(urls)),
m: make(map[uint64]*url.URL),
mu: new(sync.RWMutex),
rr: rr,
}, nil
}
func (i *iphash) Next(in *url.URL) *url.URL {
hashN := xxhash.Sum64(*(*[]byte)(unsafe.Pointer(&in.Host))) % i.cnt
i.mu.RLock()
if url, ok := i.m[hashN]; ok {
i.mu.RUnlock()
return url
}
i.mu.RUnlock()
url := i.rr.Next()
i.mu.Lock()
i.m[hashN] = url
i.mu.Unlock()
return url
}