-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcache.go
More file actions
85 lines (69 loc) · 1.29 KB
/
cache.go
File metadata and controls
85 lines (69 loc) · 1.29 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
package main
import (
"sync"
"time"
)
type cacheField struct {
value any
expire int64
}
type Cache struct {
cache map[string]cacheField
mutex sync.RWMutex
}
func NewCache() *Cache {
cache := &Cache{
cache: make(map[string]cacheField),
}
cache.cleanup()
return cache
}
func (c *Cache) Set(key string, value any, ttl int64) {
c.mutex.Lock()
defer c.mutex.Unlock()
expire := time.Now().Add(time.Duration(ttl) * time.Second).Unix()
c.cache[key] = cacheField{
value: value,
expire: expire,
}
}
func (c *Cache) Get(key string) (any, bool) {
c.mutex.RLock()
field, ok := c.cache[key]
if !ok {
c.mutex.RUnlock()
return nil, false
}
if time.Now().Unix() > field.expire {
c.mutex.RUnlock()
c.Delete(key)
return nil, false
}
c.mutex.RUnlock()
return field.value, true
}
func (c *Cache) Delete(key string) {
c.mutex.Lock()
defer c.mutex.Unlock()
delete(c.cache, key)
}
func (c *Cache) Flush() {
c.mutex.Lock()
defer c.mutex.Unlock()
c.cache = make(map[string]cacheField, 0)
}
func (c *Cache) cleanup() {
go func() {
ticker := time.NewTicker(24 * time.Hour)
defer ticker.Stop()
for range ticker.C {
c.mutex.Lock()
for key, field := range c.cache {
if time.Now().Unix() > field.expire {
delete(c.cache, key)
}
}
c.mutex.Unlock()
}
}()
}