/
gocacheclient.go
76 lines (63 loc) · 1.66 KB
/
gocacheclient.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package caches
import (
"context"
"fmt"
"time"
log "github.com/howood/kangaroochat/infrastructure/logger"
"github.com/patrickmn/go-cache"
)
const (
// NumInstance is number of instance
NumInstance = 5
// PurgeExpiredTime is time to purge cache
PurgeExpiredTime = 10
)
var gocacheConnectionMap map[int]*cache.Cache
func init() {
gocacheConnectionMap = make(map[int]*cache.Cache, 0)
for i := 0; i < NumInstance; i++ {
gocacheConnectionMap[i] = cache.New(60*time.Minute, PurgeExpiredTime*time.Minute)
}
}
// GoCacheClient struct
type GoCacheClient struct {
ctx context.Context
}
// NewGoCacheClient creates a new GoCacheClient
func NewGoCacheClient(ctx context.Context) *GoCacheClient {
ret := &GoCacheClient{ctx: ctx}
return ret
}
// Get gets from cache
func (cc *GoCacheClient) Get(key string) (interface{}, bool) {
return cc.getInstance(key).Get(key)
}
// Set puts to cache
func (cc *GoCacheClient) Set(key string, value interface{}, ttl time.Duration) error {
cc.getInstance(key).Set(key, value, ttl)
return nil
}
// Del deletes from cache
func (cc *GoCacheClient) Del(key string) error {
cc.getInstance(key).Delete(key)
return nil
}
// DelBulk bulk deletes from cache
func (cc *GoCacheClient) DelBulk(key string) error {
cc.getInstance(key).Delete(key)
return nil
}
// CloseConnect close connection
func (cc *GoCacheClient) CloseConnect() error {
return nil
}
func (cc *GoCacheClient) getInstance(key string) *cache.Cache {
// djb2 algorithm
i, hash := 0, uint32(5381)
for _, c := range key {
hash = ((hash << 5) + hash) + uint32(c)
}
i = int(hash) % NumInstance
log.Info(cc.ctx, fmt.Sprintf("get_instance: %d", i))
return gocacheConnectionMap[i]
}