-
Notifications
You must be signed in to change notification settings - Fork 0
/
cache.go
110 lines (85 loc) · 2.1 KB
/
cache.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package wredis
import (
"math/rand"
"time"
"github.com/dmitrorezn/golang-lru/v2/expirable"
"github.com/vmihailenco/go-tinylfu"
)
type Cache interface {
Get(key string) (any, bool)
Set(key string, v any, ttl ...time.Duration) bool
Del(key string)
}
type randOffset time.Duration
var rnd *rand.Rand
func init() {
rnd = rand.New(rand.NewSource(time.Now().UnixMicro()))
}
func (r randOffset) Get() time.Duration {
return time.Duration(rnd.Intn(int(r)))
}
type TTLCache struct {
ttlOffset randOffset
Cache
}
func NewTTLCache(cache Cache, ttlOffset time.Duration) *TTLCache {
return &TTLCache{
Cache: cache,
ttlOffset: randOffset(ttlOffset),
}
}
var _ Cache = TTLCache{}
func (c TTLCache) Set(key string, v any, ttl ...time.Duration) bool {
if len(ttl) > 0 && c.ttlOffset > 0 {
ttl[0] += c.ttlOffset.Get()
}
return c.Cache.Set(key, v, ttl...)
}
type LRUCache struct {
cache *expirable.LRU[string, any]
}
func NewLRUCache(size int, onEvict callback[string, any], ttl time.Duration) *LRUCache {
return &LRUCache{
cache: expirable.NewLRU[string, any](size, onEvict.Call, ttl),
}
}
func (lfuc LRUCache) Get(key string) (any, bool) {
return lfuc.cache.Get(key)
}
func (lfuc LRUCache) Set(key string, v any, ttl ...time.Duration) bool {
return lfuc.cache.Set(key, v, ttl...)
}
func (lfuc LRUCache) Del(key string) {
lfuc.cache.Remove(key)
}
var _ Cache = LRUCache{}
type LFUCache struct {
onEvict callback[string, any]
ttl time.Duration
cache *tinylfu.SyncT
}
func NewLFUCache(size int, samples int, onEvict callback[string, any], ttl time.Duration) *LFUCache {
return &LFUCache{
onEvict: onEvict,
ttl: ttl,
cache: tinylfu.NewSync(size, samples),
}
}
func (lfuc LFUCache) Get(key string) (any, bool) {
return lfuc.cache.Get(key)
}
func (lfuc LFUCache) Set(key string, v any, ttl ...time.Duration) bool {
lfuc.cache.Set(&tinylfu.Item{
Key: key,
Value: v,
OnEvict: func() {
lfuc.onEvict.Call(key, v)
},
ExpireAt: time.Now().Add(append(ttl, lfuc.ttl)[0]),
})
return false
}
func (lfuc LFUCache) Del(key string) {
lfuc.cache.Del(key)
}
var _ Cache = LFUCache{}