-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathm.go
More file actions
93 lines (82 loc) · 1.63 KB
/
m.go
File metadata and controls
93 lines (82 loc) · 1.63 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
86
87
88
89
90
91
92
93
package intcache
import (
"sync"
"time"
)
type item struct {
mu sync.RWMutex
expireAt time.Time
count int
}
func (it *item) expired(t time.Time) bool {
it.mu.RLock()
defer it.mu.RUnlock()
return t.After(it.expireAt)
}
type Cache struct {
onEvicted func(any, int)
cleanupInterval time.Duration
stop chan bool
items sync.Map
}
func (c *Cache) Init(cleanupInterval time.Duration, onEvicted func(any, int)) {
c.cleanupInterval = cleanupInterval
c.stop = make(chan bool)
c.onEvicted = onEvicted
go c.loopClean()
}
func (c *Cache) Stop() {
c.stop <- true
}
func (c *Cache) Incr(key string, dur time.Duration) int {
if val, ok := c.items.Load(key); ok {
if it, ok := val.(*item); ok && it != nil {
it.mu.Lock()
defer it.mu.Unlock()
it.count++
return it.count
}
}
c.items.Store(key, &item{expireAt: time.Now().Add(dur), count: 1})
return 1
}
func (c *Cache) loopClean() {
ticker := time.NewTicker(c.cleanupInterval)
for {
select {
case <-ticker.C:
c.deleteExpired()
case <-c.stop:
ticker.Stop()
return
}
}
}
func (c *Cache) deleteExpired() {
now := time.Now()
if c.onEvicted != nil {
c.items.Range(func(key, value any) bool {
if it, ok := value.(*item); ok && it != nil {
if it.expired(now) {
if _, loaded := c.items.LoadAndDelete(key); loaded {
c.onEvicted(key, it.count)
}
}
} else {
c.items.Delete(key)
}
return true
})
} else {
c.items.Range(func(key, value any) bool {
if it, ok := value.(*item); ok && it != nil {
if it.expired(now) {
c.items.Delete(key)
}
} else {
c.items.Delete(key)
}
return true
})
}
}