-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcache.go
More file actions
83 lines (69 loc) · 1.29 KB
/
cache.go
File metadata and controls
83 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
package sync_cache
import (
"sync"
"time"
)
type CacheItem struct {
Value interface{}
Expiration int64
}
type Cache struct {
data *sync.Map
janitor *janitor
}
func NewCache(cleanupInterval time.Duration) *Cache {
var cache = &Cache{
data: new(sync.Map),
janitor: &janitor{
interval: cleanupInterval,
stop: make(chan bool),
},
}
go cache.janitor.Run(cache)
return cache
}
func (c *Cache) Get(key string) (any, bool) {
value, ok := c.data.Load(key)
if !ok {
return nil, false // Key not found
}
return (value).(*CacheItem).Value, true
}
func (c *Cache) Set(key string, value any, d time.Duration) {
var e int64
if d > 0 {
e = time.Now().Add(d).UnixNano()
}
item := &CacheItem{
Value: value,
Expiration: e,
}
c.data.Store(key, item)
}
func (c *Cache) Delete(key string) {
c.data.Delete(key)
}
func (c *Cache) Clear() {
c.data.Range(func(key, _ any) bool {
c.data.Delete(key)
return true
})
}
func (c *Cache) Size() int {
size := 0
c.data.Range(func(_, _ any) bool {
size++
return true
})
return size
}
func (c *Cache) work() {
now := time.Now().UnixNano()
c.data.Range(func(key, value any) bool {
var expiration = value.(*CacheItem).Expiration
if now > expiration && expiration != 0 {
c.Delete(key.(string))
}
return true
})
}