-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhot_cache.go
126 lines (107 loc) · 2.56 KB
/
hot_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
package cache
import (
"bytes"
"container/list"
"fmt"
"sync"
"time"
)
// Key key
type Key interface{}
func (r *Record) String() string {
return fmt.Sprintf(
"key:%v, last visit time:%s", r.listIdx.Value,
r.lastVisitTime.Format("2006-01-02 15:04:05"))
}
// Record record
type Record struct {
listIdx *list.Element
val interface{}
lastVisitTime time.Time
}
// LRUCache lru cache
type LRUCache struct {
// maxNum is the maximum number of cache entries before
maxNum int
lock *sync.Mutex
keyOrder *list.List
contents map[Key]*Record
timeoutInSeconds int
}
// NewLRUCache create LRUCache instance
func NewLRUCache(num, timeoutInSeconds int) (rc *LRUCache) {
if num < 1 {
num = 0
}
return &LRUCache{
maxNum: num,
lock: &sync.Mutex{},
keyOrder: list.New(),
contents: make(map[Key]*Record),
timeoutInSeconds: timeoutInSeconds,
}
}
func (lc LRUCache) String() string {
var buf bytes.Buffer
fmt.Fprintf(&buf, "there are %d record in LRU cache. ", lc.keyOrder.Len())
for _, record := range lc.contents {
fmt.Fprint(&buf, fmt.Sprintf("%s; ", record))
}
return buf.String()
}
// Set add kv item to lru cache
func (lc *LRUCache) Set(key, val interface{}) {
lc.lock.Lock()
defer lc.lock.Unlock()
record, ok := lc.contents[key]
if ok {
// update value in element
record.val = val
lc.keyOrder.MoveToFront(record.listIdx)
} else {
// add new element
if lc.keyOrder.Len() >= lc.maxNum {
leastUsedElement := lc.keyOrder.Back()
delete(lc.contents, key)
lc.keyOrder.Remove(leastUsedElement)
}
record = new(Record)
record.val = val
record.listIdx = lc.keyOrder.PushFront(key)
lc.contents[key] = record
}
record.lastVisitTime = time.Now()
}
// Get get value by key
func (lc *LRUCache) Get(key interface{}) (val interface{}) {
lc.lock.Lock()
defer lc.lock.Unlock()
record, ok := lc.contents[key]
if ok {
// check if is expired record
now := time.Now()
behindSeconds := time.Second * time.Duration(lc.timeoutInSeconds)
if now.After(record.lastVisitTime.Add(behindSeconds)) {
lc.keyOrder.Remove(record.listIdx)
delete(lc.contents, key)
return nil
}
// reorder key position
lc.keyOrder.PushFront(key)
val = record.val
record.lastVisitTime = now
return val
}
return nil
}
// Remove remove value by key
func (lc *LRUCache) Remove(key interface{}) (val interface{}) {
lc.lock.Lock()
defer lc.lock.Unlock()
record, ok := lc.contents[key]
if ok {
lc.keyOrder.Remove(record.listIdx)
delete(lc.contents, key)
}
return
}