-
-
Notifications
You must be signed in to change notification settings - Fork 478
/
cache.go
93 lines (77 loc) · 1.37 KB
/
cache.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
82
83
84
85
86
87
88
89
90
91
92
93
package agent
import (
"sync"
"time"
)
type cacheEntry struct {
value string
maxExpire time.Time
expire time.Time
created time.Time
}
func (ce *cacheEntry) isExpired() bool {
if time.Now().After(ce.maxExpire) {
return true
}
if time.Now().After(ce.expire) {
return true
}
return false
}
type cache struct {
sync.Mutex
ttl time.Duration
maxTTL time.Duration
entries map[string]cacheEntry
}
func (c *cache) get(key string) (string, bool) {
c.Lock()
defer c.Unlock()
if c.entries == nil {
return "", false
}
ce, found := c.entries[key]
if !found {
// not found
return "", false
}
if ce.isExpired() {
// expired
return "", false
}
ce.expire = time.Now().Add(c.ttl)
c.entries[key] = ce
return ce.value, true
}
func (c *cache) purgeExpired() {
for k, ce := range c.entries {
if ce.isExpired() {
delete(c.entries, k)
}
}
}
func (c *cache) set(key, value string) {
c.Lock()
defer c.Unlock()
if c.entries == nil {
c.entries = make(map[string]cacheEntry, 10)
}
now := time.Now()
c.entries[key] = cacheEntry{
value: value,
maxExpire: now.Add(c.maxTTL),
expire: now.Add(c.ttl),
created: now,
}
c.purgeExpired()
}
func (c *cache) remove(key string) {
c.Lock()
defer c.Unlock()
delete(c.entries, key)
}
func (c *cache) purge() {
c.Lock()
defer c.Unlock()
c.entries = make(map[string]cacheEntry, 10)
}