-
Notifications
You must be signed in to change notification settings - Fork 18
/
ramcache.go
69 lines (58 loc) · 1.45 KB
/
ramcache.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
package D
import (
"fmt"
"time"
"github.com/allegro/bigcache"
"github.com/kpango/fastime"
"github.com/kokizzu/gotro/L"
cmap "github.com/orcaman/concurrent-map"
)
type RamCache struct {
evictionLogic *bigcache.BigCache
store cmap.ConcurrentMap
expireSec int64
}
func NewRamCache(dur time.Duration, sizeMB int) *RamCache {
cfg := bigcache.DefaultConfig(dur)
cfg.HardMaxCacheSize = sizeMB
res := &RamCache{
store: cmap.New(),
expireSec: int64(dur.Seconds()),
}
cfg.OnRemove = func(key string, entry []byte) {
res.store.Remove(key)
}
expireLogic, err := bigcache.NewBigCache(cfg)
L.PanicIf(err, `bigcache.NewBigCache failed`)
res.evictionLogic = expireLogic
return res
}
func (r *RamCache) Set(key string, value any) {
suffix := r.secondSuffix()
if r.evictionLogic != nil && r.evictionLogic.Set(key+suffix, []byte{1}) == nil {
r.store.Set(key+suffix, value)
}
}
func (r *RamCache) ClearAll() {
r.store.Clear()
L.IsError(r.evictionLogic.Reset(), `RamCache.ClearAll`)
}
func (r *RamCache) Get(key string) any {
res, ok := r.store.Get(key + r.secondSuffix())
if !ok {
return nil
}
return res
}
func (r *RamCache) Delete(k string) {
suffix := r.secondSuffix()
r.store.Remove(k + suffix)
L.IsError(r.evictionLogic.Delete(k+suffix), `RamCache.Delete`)
}
// force evict every n seconds
func (r *RamCache) secondSuffix() string {
if r.expireSec < 2 {
return ``
}
return `|` + fmt.Sprint(fastime.UnixNow()/r.expireSec)
}