-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcache.go
127 lines (108 loc) · 2.06 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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
package gossip
import (
"container/list"
"github.com/google/uuid"
"sync"
"time"
)
// LRUCache 消息id的过期+lru缓存
type LRUCache struct {
Cap int
TTL time.Duration
cache map[string]*list.Element
ll list.List
locker sync.RWMutex
}
type entry struct {
key string
expire time.Time
}
func NewCache(cap int, ttl time.Duration) *LRUCache {
c := &LRUCache{
Cap: cap,
TTL: ttl,
ll: list.List{},
cache: make(map[string]*list.Element),
locker: sync.RWMutex{},
}
go c.trigger()
return c
}
func (c *LRUCache) Set(key string) {
c.locker.Lock()
element, exist := c.cache[key]
if !exist {
element = c.ll.PushFront(&entry{key: key, expire: time.Now().Add(c.TTL)})
c.cache[key] = element
} else {
// 更新过期时间
element.Value.(*entry).expire = time.Now().Add(c.TTL)
// 移到队首
c.ll.MoveToFront(element)
}
c.locker.Unlock()
c.locker.RLock()
length := c.ll.Len()
c.locker.RUnlock()
if c.Cap > 0 && length > c.Cap {
c.removeOldest()
return
}
}
func (c *LRUCache) NewID() string {
id := uuid.NewString()
c.Set(id)
return id
}
func (c *LRUCache) Has(key string) bool {
c.locker.RLock()
_, exist := c.cache[key]
c.locker.RUnlock()
return exist
}
func (c *LRUCache) removeOldest() {
c.locker.Lock()
el := c.ll.Back()
if el == nil {
c.locker.Unlock()
return
}
c.ll.Remove(el)
e := el.Value.(*entry)
delete(c.cache, e.key)
c.locker.Unlock()
}
func (c *LRUCache) trigger() {
t := time.NewTicker(time.Second * 5)
for {
select {
case <-t.C:
expired := map[string]*list.Element{}
// 从后往前检查:越接近过期时间的越靠后
for {
c.locker.RLock()
element := c.ll.Back()
c.locker.RUnlock()
if element == nil {
break
}
e := element.Value.(*entry)
if time.Now().Sub(e.expire) >= 0 {
// 过期了
expired[e.key] = element
continue
}
break
}
if len(expired) == 0 {
break
}
c.locker.Lock()
for key, element := range expired {
c.ll.Remove(element)
delete(c.cache, key)
}
c.locker.Unlock()
}
}
}