-
Notifications
You must be signed in to change notification settings - Fork 6
/
memory.go
217 lines (193 loc) · 4.83 KB
/
memory.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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
// Copyright 2014 beego Author. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cache
import (
"context"
"fmt"
"strings"
"sync"
"time"
berror "github.com/beego/beego-error/v2"
)
// DefaultEvery sets a timer for how often to recycle the expired cache items in memory (in seconds)
//var DefaultEvery = 60 // 1 minute
// MemoryItem stores memory cache item.
type MemoryItem struct {
val interface{}
createdTime time.Time
lifespan time.Duration
}
func (mi *MemoryItem) isExpire() bool {
// 0 means forever
if mi.lifespan == 0 {
return false
}
return time.Since(mi.createdTime) > mi.lifespan
}
// MemoryCache is a memory cache adapter.
// Contains a RW locker for safe map storage.
type MemoryCache struct {
sync.RWMutex
dur time.Duration
items map[string]*MemoryItem
Every int // run an expiration check Every clock time
}
// NewMemoryCache returns a new MemoryCache.
func NewMemoryCache(interval int) Cache {
res := &MemoryCache{
Every: interval,
items: make(map[string]*MemoryItem),
dur: time.Duration(interval) * time.Second,
}
go res.vacuum()
return res
}
// Get returns cache from memory.
// If non-existent or expired, return nil.
func (bc *MemoryCache) Get(ctx context.Context, key string) (interface{}, error) {
bc.RLock()
defer bc.RUnlock()
if itm, ok := bc.items[key]; ok {
if itm.isExpire() {
return nil, ErrKeyExpired
}
return itm.val, nil
}
return nil, ErrKeyNotExist
}
// GetMulti gets caches from memory.
// If non-existent or expired, return nil.
func (bc *MemoryCache) GetMulti(ctx context.Context, keys []string) ([]interface{}, error) {
rc := make([]interface{}, len(keys))
keysErr := make([]string, 0)
for i, ki := range keys {
val, err := bc.Get(context.Background(), ki)
if err != nil {
keysErr = append(keysErr, fmt.Sprintf("key [%s] error: %s", ki, err.Error()))
continue
}
rc[i] = val
}
if len(keysErr) == 0 {
return rc, nil
}
return rc, berror.Error(MultiGetFailed, strings.Join(keysErr, "; "))
}
// Put puts cache into memory.
// If lifespan is 0, it will never overwrite this value unless restarted
func (bc *MemoryCache) Put(ctx context.Context, key string, val interface{}, timeout time.Duration) error {
bc.Lock()
defer bc.Unlock()
bc.items[key] = &MemoryItem{
val: val,
createdTime: time.Now(),
lifespan: timeout,
}
return nil
}
// Delete cache in memory.
// If the key is not found, it will not return error
func (bc *MemoryCache) Delete(ctx context.Context, key string) error {
bc.Lock()
defer bc.Unlock()
delete(bc.items, key)
return nil
}
// Incr increases cache counter in memory.
// Supports int,int32,int64,uint,uint32,uint64.
func (bc *MemoryCache) Incr(ctx context.Context, key string) error {
bc.Lock()
defer bc.Unlock()
itm, ok := bc.items[key]
if !ok {
return ErrKeyNotExist
}
val, err := incr(itm.val)
if err != nil {
return err
}
itm.val = val
return nil
}
// Decr decreases counter in memory.
func (bc *MemoryCache) Decr(ctx context.Context, key string) error {
bc.Lock()
defer bc.Unlock()
itm, ok := bc.items[key]
if !ok {
return ErrKeyNotExist
}
val, err := decr(itm.val)
if err != nil {
return err
}
itm.val = val
return nil
}
// IsExist checks if cache exists in memory.
func (bc *MemoryCache) IsExist(ctx context.Context, key string) (bool, error) {
bc.RLock()
defer bc.RUnlock()
if v, ok := bc.items[key]; ok {
return !v.isExpire(), nil
}
return false, nil
}
// ClearAll deletes all cache in memory.
func (bc *MemoryCache) ClearAll(context.Context) error {
bc.Lock()
defer bc.Unlock()
bc.items = make(map[string]*MemoryItem)
return nil
}
// check expiration.
func (bc *MemoryCache) vacuum() {
bc.RLock()
every := bc.Every
bc.RUnlock()
if every < 1 {
return
}
for {
<-time.After(bc.dur)
bc.RLock()
if bc.items == nil {
bc.RUnlock()
return
}
bc.RUnlock()
if keys := bc.expiredKeys(); len(keys) != 0 {
bc.clearItems(keys)
}
}
}
// expiredKeys returns keys list which are expired.
func (bc *MemoryCache) expiredKeys() (keys []string) {
bc.RLock()
defer bc.RUnlock()
for key, itm := range bc.items {
if itm.isExpire() {
keys = append(keys, key)
}
}
return
}
// ClearItems removes all items who's key is in keys
func (bc *MemoryCache) clearItems(keys []string) {
bc.Lock()
defer bc.Unlock()
for _, key := range keys {
delete(bc.items, key)
}
}