-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcache-map-mem.go
64 lines (55 loc) · 1.13 KB
/
cache-map-mem.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
package gofnext
import (
"sync"
"time"
)
type cachedValue struct {
val interface{}
createdAt time.Time
err error
}
type memCacheMap struct {
*sync.Map
// mu sync.RWMutex
ttl time.Duration
errTtl time.Duration
}
func newCacheMapMem(ttl time.Duration) *memCacheMap {
return &memCacheMap{
ttl: ttl,
Map: &sync.Map{},
}
}
func (m *memCacheMap) Store(key, value any, err error) {
el := cachedValue{
val: value,
createdAt: time.Now(),
err: err,
}
m.Map.Store(key, &el)
}
func (m *memCacheMap) Load(key any) (value any, existed bool, err error) {
elInter, existed := m.Map.Load(key)
if existed {
el := elInter.(*cachedValue)
if (m.ttl > 0 && time.Since(el.createdAt) > m.ttl) ||
(el.err != nil && m.errTtl >= 0 && time.Since(el.createdAt) > m.errTtl) {
m.Map.Delete(key)
existed = false
} else {
return el.val, existed, el.err
}
}
return
}
func (m *memCacheMap) SetTTL(ttl time.Duration) CacheMap {
m.ttl = ttl
return m
}
func (m *memCacheMap) SetErrTTL(errTTL time.Duration) CacheMap {
m.errTtl = errTTL
return m
}
func (m *memCacheMap) NeedMarshal() bool {
return false
}