-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathttlcache.go
More file actions
117 lines (91 loc) · 1.71 KB
/
Copy pathttlcache.go
File metadata and controls
117 lines (91 loc) · 1.71 KB
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
111
112
113
114
115
116
117
package ttlcache
import (
"errors"
"sync"
"time"
)
var (
errRunning = errors.New("already running")
errNotRunning = errors.New("not running")
)
type item[V any] struct {
value V
expiry time.Time
}
type Cache[K comparable, V any] struct {
items map[K]item[V]
ttl time.Duration
mu sync.RWMutex
cleanup chan struct{}
}
func NewCache[K comparable, V any](ttl time.Duration) *Cache[K, V] {
return &Cache[K, V]{
items: make(map[K]item[V]),
ttl: ttl,
}
}
func (c *Cache[K, V]) Set(key K, value V) {
c.mu.Lock()
defer c.mu.Unlock()
c.items[key] = item[V]{
value: value,
expiry: time.Now().Add(c.ttl),
}
}
func (c *Cache[K, V]) Get(key K) (V, bool) {
c.mu.RLock()
defer c.mu.RUnlock()
item, found := c.items[key]
if !found {
var zero V
return zero, false
}
if time.Now().After(item.expiry) {
var zero V
return zero, false
}
return item.value, true
}
func (c *Cache[K, V]) DeleteExpired() {
c.mu.Lock()
defer c.mu.Unlock()
now := time.Now()
for k, v := range c.items {
if now.After(v.expiry) {
delete(c.items, k)
}
}
}
func (c *Cache[K, V]) StartCleanup(interval time.Duration) error {
c.mu.Lock()
defer c.mu.Unlock()
if c.cleanup != nil {
return errRunning
}
stop := make(chan struct{})
c.cleanup = stop
go c.doCleanup(interval, stop)
return nil
}
func (c *Cache[K, V]) StopCleanup() error {
c.mu.Lock()
defer c.mu.Unlock()
if c.cleanup == nil {
return errNotRunning
}
close(c.cleanup)
c.cleanup = nil
return nil
}
func (c *Cache[K, V]) doCleanup(interval time.Duration, stop <-chan struct{}) {
ticker := time.NewTicker(interval)
for {
select {
case <-ticker.C:
c.DeleteExpired()
case <-stop:
ticker.Stop()
return
}
}
}