-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathutil_cache.go
102 lines (82 loc) · 1.71 KB
/
util_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
94
95
96
97
98
99
100
101
102
package prophet
import (
"sync"
"time"
)
type cacheItem struct {
key uint64
value interface{}
expire time.Time
}
type resourceFreezeCache struct {
sync.RWMutex
items map[uint64]cacheItem
ttl time.Duration
gcInterval time.Duration
}
// newResourceFreezeCache returns a new expired resource freeze cache.
func newResourceFreezeCache(gcInterval time.Duration, ttl time.Duration) *resourceFreezeCache {
c := &resourceFreezeCache{
items: make(map[uint64]cacheItem),
ttl: ttl,
gcInterval: gcInterval,
}
return c
}
func (c *resourceFreezeCache) get(key uint64) (interface{}, bool) {
c.RLock()
defer c.RUnlock()
item, ok := c.items[key]
if !ok {
return nil, false
}
if item.expire.Before(time.Now()) {
return nil, false
}
return item.value, true
}
func (c *resourceFreezeCache) set(key uint64, value interface{}) {
c.setWithTTL(key, value, c.ttl)
}
func (c *resourceFreezeCache) setWithTTL(key uint64, value interface{}, ttl time.Duration) {
c.Lock()
defer c.Unlock()
c.items[key] = cacheItem{
value: value,
expire: time.Now().Add(ttl),
}
}
func (c *resourceFreezeCache) delete(key uint64) {
c.Lock()
defer c.Unlock()
delete(c.items, key)
}
func (c *resourceFreezeCache) count() int {
c.RLock()
defer c.RUnlock()
return len(c.items)
}
func (c *resourceFreezeCache) startGC() {
go c.doGC()
}
func (c *resourceFreezeCache) doGC() {
ticker := time.NewTicker(c.gcInterval)
defer ticker.Stop()
for {
select {
case <-ticker.C:
count := 0
now := time.Now()
c.Lock()
for key := range c.items {
if value, ok := c.items[key]; ok {
if value.expire.Before(now) {
count++
delete(c.items, key)
}
}
}
c.Unlock()
}
}
}