-
Notifications
You must be signed in to change notification settings - Fork 0
/
memory_cache.go
198 lines (161 loc) · 4.08 KB
/
memory_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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
package memorycache
import (
"context"
"encoding/gob"
"math"
"os"
"sync"
"time"
)
// MemoryCache cache
type MemoryCache struct {
options MemoryCacheOptions
store map[string]memoryCacheEntry
mutex sync.RWMutex
ctx context.Context
cancel context.CancelFunc
}
// Get provide entry value by key
func (m *MemoryCache) Get(key string) (value interface{}, ok bool) {
m.mutex.RLock()
defer m.mutex.RUnlock()
entry, ok := m.store[key]
if ok && time.Since(entry.Expiration) >= 0 {
return nil, false
}
return entry.Value, ok
}
// Set add entry or update value by key
func (m *MemoryCache) Set(key string, value interface{}, options MemoryCacheEntryOptions) {
m.mutex.Lock()
defer m.mutex.Unlock()
// удаление слабой записи из кеша при достижении лимита
if m.options.LimitEntries != 0 && len(m.store) >= m.options.LimitEntries {
if _, ok := m.store[key]; !ok {
now := time.Now()
var wimpEntry string
var wimpEntryExpiration time.Time = time.Now()
var wimpEntryDurability MemoryCacheEntryDurability = math.MaxInt
// алгоритм, исходит из того, что всегда получит запись т.к. сравнивает стойкость с MaxInt
for key, entry := range m.store {
if now.Sub(entry.Expiration) >= 0 {
wimpEntry = key
break
}
if entry.Durability < wimpEntryDurability {
wimpEntryDurability = entry.Durability
wimpEntryExpiration = entry.Expiration
wimpEntry = key
continue
}
if entry.Durability == wimpEntryDurability {
if wimpEntryExpiration.Sub(entry.Expiration) > 0 {
wimpEntryDurability = entry.Durability
wimpEntryExpiration = entry.Expiration
wimpEntry = key
}
}
}
delete(m.store, wimpEntry)
}
}
if options.Lifetime > 0 {
m.store[key] = memoryCacheEntry{
Value: value,
Expiration: time.Now().Add(options.Lifetime),
Durability: options.Durability,
}
}
}
// Del delete entry by key
func (m *MemoryCache) Del(key string) {
m.mutex.Lock()
defer m.mutex.Unlock()
delete(m.store, key)
}
// Count provide count entries in cache
func (m *MemoryCache) Count() (count int) {
m.mutex.RLock()
defer m.mutex.RUnlock()
return len(m.store)
}
// Reset remove all entries from cache
func (m *MemoryCache) Reset() {
m.mutex.Lock()
defer m.mutex.Unlock()
m.store = make(map[string]memoryCacheEntry)
}
// startCleanup start cleaning mechanism
func (m *MemoryCache) startCleanup() {
for {
select {
case <-m.ctx.Done(): // wait for service stop
return
case <-time.After(m.options.CleanupInterval): // wait for cleanup timeout
m.сleanup()
}
}
}
// сleanup cleaning up expired records
func (m *MemoryCache) сleanup() {
m.mutex.Lock()
defer m.mutex.Unlock()
if m.store != nil {
for key, entry := range m.store {
if time.Since(entry.Expiration) >= 0 {
delete(m.store, key)
}
}
}
}
// New construct and load cache data from file if set FileName
func New(options MemoryCacheOptions) (memorycache *MemoryCache) {
ctx, cancel := context.WithCancel(context.Background())
memorycache = &MemoryCache{
store: make(map[string]memoryCacheEntry),
options: options,
ctx: ctx,
cancel: cancel,
}
if options.FileName != "" {
memorycache.load()
}
if options.CleanupInterval > 0 {
go memorycache.startCleanup()
}
return memorycache
}
// Close destruct and save cache data in file if set FileName
func (m *MemoryCache) Close() {
if m.cancel != nil {
m.cancel()
}
if m.options.FileName != "" {
m.save()
}
m.mutex.Lock()
defer m.mutex.Unlock()
m.store = nil
}
// load load cache data from file
func (m *MemoryCache) load() {
m.mutex.Lock()
defer m.mutex.Unlock()
file, err := os.Open(m.options.FileName)
if err == nil {
defer file.Close()
decoder := gob.NewDecoder(file)
decoder.Decode(&m.store)
}
}
// save save cache data to file
func (m *MemoryCache) save() {
m.mutex.Lock()
defer m.mutex.Unlock()
file, err := os.Create(m.options.FileName)
if err == nil {
defer file.Close()
encoder := gob.NewEncoder(file)
encoder.Encode(m.store)
}
}