1
1
package cache
2
2
3
3
import (
4
+ "container/list"
4
5
"context"
5
6
"sync"
6
7
@@ -13,6 +14,68 @@ type Store interface {
13
14
Set (ctx context.Context , key int , value float32 )
14
15
}
15
16
17
+ // LRU Cache 实现
18
+ type lruStore struct {
19
+ mu sync.RWMutex
20
+ capacity int
21
+ cache map [int ]* list.Element
22
+ lru * list.List
23
+ }
24
+
25
+ type entry struct {
26
+ key int
27
+ value float32
28
+ }
29
+
30
+ func NewLRUStore (capacity int ) Store {
31
+ return & lruStore {
32
+ capacity : capacity ,
33
+ cache : make (map [int ]* list.Element ),
34
+ lru : list .New (),
35
+ }
36
+ }
37
+
38
+ func (l * lruStore ) Get (ctx context.Context , key int ) (float32 , bool ) {
39
+ l .mu .RLock ()
40
+ defer l .mu .RUnlock ()
41
+
42
+ if elem , ok := l .cache [key ]; ok {
43
+ l .lru .MoveToFront (elem )
44
+ sp := trace .SpanFromContext (ctx )
45
+ sp .SetAttributes (attribute .Int ("cache.grid" , key ), attribute .Bool ("cache.hit" , true ))
46
+ return elem .Value .(* entry ).value , true
47
+ }
48
+
49
+ sp := trace .SpanFromContext (ctx )
50
+ sp .SetAttributes (attribute .Int ("cache.grid" , key ), attribute .Bool ("cache.hit" , false ))
51
+ return 0 , false
52
+ }
53
+
54
+ func (l * lruStore ) Set (ctx context.Context , key int , value float32 ) {
55
+ l .mu .Lock ()
56
+ defer l .mu .Unlock ()
57
+
58
+ if elem , ok := l .cache [key ]; ok {
59
+ l .lru .MoveToFront (elem )
60
+ elem .Value .(* entry ).value = value
61
+ return
62
+ }
63
+
64
+ // 如果缓存已满,删除最久未使用的条目
65
+ if l .lru .Len () >= l .capacity {
66
+ oldest := l .lru .Back ()
67
+ if oldest != nil {
68
+ delete (l .cache , oldest .Value .(* entry ).key )
69
+ l .lru .Remove (oldest )
70
+ }
71
+ }
72
+
73
+ // 添加新条目
74
+ elem := l .lru .PushFront (& entry {key : key , value : value })
75
+ l .cache [key ] = elem
76
+ }
77
+
78
+ // 简单的 map 实现
16
79
type mapStore struct {
17
80
mu sync.RWMutex
18
81
cache map [int ]float32
0 commit comments