-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcache.go
More file actions
134 lines (115 loc) · 2.42 KB
/
cache.go
File metadata and controls
134 lines (115 loc) · 2.42 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
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
128
129
130
131
132
133
134
package spellsql
import (
"container/list"
"sync"
)
const (
lruSize = 2 << 8 // lru 最大值
)
type LRUCache struct {
rwMu sync.RWMutex
maxSize int
delMapCount int // 记录 delete map 的次数, 当次数大于 2*lruSize 重建下 nodeMap, 防止 delete 没有释放内存
nodeMap map[interface{}]*list.Element
list *list.List
deleteCallBackFn func(key, value interface{}) // 删除回调
}
func NewLRU(max ...int) *LRUCache {
defaultMax := lruSize
if len(max) > 0 {
defaultMax = max[0]
}
return &LRUCache{
maxSize: defaultMax,
nodeMap: make(map[interface{}]*list.Element, defaultMax),
list: list.New(),
}
}
func (l *LRUCache) SetDelCallBackFn(f func(key, value interface{})) {
l.deleteCallBackFn = f
}
func (l *LRUCache) Store(key, value interface{}) {
l.rwMu.Lock()
defer l.rwMu.Unlock()
node, ok := l.nodeMap[key]
if ok {
l.list.MoveToFront(node)
return
}
// 不存在
head := l.list.PushFront(value)
l.nodeMap[key] = head
// 判断是否已满, 满了就删除最后一个
if l.list.Len() > l.maxSize {
l.delete(nil, l.list.Back())
}
}
func (l *LRUCache) Load(key interface{}) (data interface{}, ok bool) {
l.rwMu.Lock()
defer l.rwMu.Unlock()
node, ok := l.nodeMap[key]
if !ok {
return
}
data = node.Value
l.list.MoveToFront(node)
return
}
func (l *LRUCache) Delete(key interface{}) {
l.rwMu.Lock()
defer l.rwMu.Unlock()
node, ok := l.nodeMap[key]
if !ok {
return
}
l.delete(key, node)
}
func (l *LRUCache) delete(key interface{}, node *list.Element) {
if key == nil {
for k, v := range l.nodeMap {
if v == node {
key = k
break
}
}
}
delete(l.nodeMap, key)
l.list.Remove(node)
if l.deleteCallBackFn != nil {
l.deleteCallBackFn(key, node.Value)
}
// 重建 map
if l.delMapCount > 3*l.maxSize {
tmp := l.nodeMap
l.nodeMap = make(map[interface{}]*list.Element, len(tmp))
for k, v := range tmp {
l.nodeMap[k] = v
}
l.delMapCount = 0
} else {
l.delMapCount++
}
}
// Len 长度
// return -1 的话, 长度不正确
func (l *LRUCache) Len() int {
l.rwMu.RLock()
defer l.rwMu.RUnlock()
if l.list.Len() != len(l.nodeMap) {
return -1
}
return l.list.Len()
}
func (l *LRUCache) Dump() string {
head := l.list.Front()
buf := getTmpBuf()
defer putTmpBuf(buf)
for head != nil {
buf.WriteString(Str(head.Value))
head = head.Next()
if head != nil {
buf.WriteByte('\n')
}
}
return buf.String()
}