forked from go-redis/cache
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlocal.go
81 lines (64 loc) · 1.28 KB
/
local.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
package cache
import (
"math/rand"
"sync"
"time"
"github.com/vmihailenco/go-tinylfu"
)
type LocalCache interface {
Set(key string, data []byte)
Get(key string) ([]byte, bool)
Del(key string)
}
type TinyLFU struct {
mu sync.Mutex
rand *rand.Rand
lfu *tinylfu.T
ttl time.Duration
offset time.Duration
}
var _ LocalCache = (*TinyLFU)(nil)
func NewTinyLFU(size int, ttl time.Duration) *TinyLFU {
const maxOffset = 10 * time.Second
offset := ttl / 10
if offset > maxOffset {
offset = maxOffset
}
return &TinyLFU{
rand: rand.New(rand.NewSource(time.Now().UnixNano())),
lfu: tinylfu.New(size, 100000),
ttl: ttl,
offset: offset,
}
}
func (c *TinyLFU) UseRandomizedTTL(offset time.Duration) {
c.offset = offset
}
func (c *TinyLFU) Set(key string, b []byte) {
c.mu.Lock()
defer c.mu.Unlock()
ttl := c.ttl
if c.offset > 0 {
ttl += time.Duration(c.rand.Int63n(int64(c.offset)))
}
c.lfu.Set(&tinylfu.Item{
Key: key,
Value: b,
ExpireAt: time.Now().Add(ttl),
})
}
func (c *TinyLFU) Get(key string) ([]byte, bool) {
c.mu.Lock()
defer c.mu.Unlock()
val, ok := c.lfu.Get(key)
if !ok {
return nil, false
}
b := val.([]byte)
return b, true
}
func (c *TinyLFU) Del(key string) {
c.mu.Lock()
defer c.mu.Unlock()
c.lfu.Del(key)
}