-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmemory.go
More file actions
230 lines (205 loc) · 4.32 KB
/
memory.go
File metadata and controls
230 lines (205 loc) · 4.32 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
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
218
219
220
221
222
223
224
225
226
227
228
229
230
package cache
import (
"errors"
"fmt"
"sync"
"time"
"github.com/go-baa/cache/lru"
)
const (
// MemoryLimit default memory size limit, 128mb
// 128 1 << 7
// 1024 1 << 10
MemoryLimit int64 = 1 << 27
// MemoryLimitMin minimum value for memory limit, 1mb
MemoryLimitMin int64 = 1 << 20
// MenoryObjectMaxSize maximum bytes for object, 1mb
MenoryObjectMaxSize int64 = 1 << 20
)
// Memory implement a memory cache adapter for cacher
type Memory struct {
Name string
Prefix string
bytes int64
bytesLimit int64
mu sync.RWMutex
store *lru.Cache
}
// NewMemory create a cache instance of memory
func NewMemory() Cacher {
return new(Memory)
}
// Exist return true if value cached by given key
func (c *Memory) Exist(key string) bool {
item := c.get(c.Prefix + key)
if item != nil {
return true
}
return false
}
// Get returns value by given key
func (c *Memory) Get(key string, out interface{}) error {
c.mu.RLock()
c.mu.RUnlock()
item := c.get(c.Prefix + key)
if item == nil {
return errors.New("cache: cache miss")
}
return item.Decode(out)
}
func (c *Memory) get(key string) *Item {
v, ok := c.store.Get(key)
if !ok {
return nil
}
item, err := v.(ItemBinary).Item()
if err != nil {
return nil
}
if item.Expired() {
c.Delete(key)
return nil
}
return item
}
// Set cache value by given key, cache ttl second
func (c *Memory) Set(key string, v interface{}, ttl int64) error {
item := NewItem(v, ttl)
b, err := item.Encode()
if err != nil {
return err
}
// if overwrite bytes count will error
// so, delete first if exist
if c.Exist(key) {
c.store.Remove(c.Prefix + key)
}
c.mu.Lock()
defer c.mu.Unlock()
l := int64(len(b))
err = c.gc(l)
if err != nil {
return err
}
c.store.Add(c.Prefix+key, b)
c.bytes += l
return nil
}
// Incr increases cached int-type value by given key as a counter
// if key not exist, before increase set value with zero
func (c *Memory) Incr(key string) (int64, error) {
item := c.get(c.Prefix + key)
if item == nil {
item = NewItem(0, 0)
}
err := item.Incr()
if err != nil {
return 0, err
}
ttl := item.TTL
if ttl > 0 {
ttl = int64((item.Expiration - time.Now().UnixNano()) / 1e9)
}
if ttl < 0 {
return 0, fmt.Errorf("cache: expired")
}
err = c.Set(key, item.Val, ttl)
if err != nil {
return 0, err
}
return item.Val.(int64), nil
}
// Decr decreases cached int-type value by given key as a counter
// if key not exist, return errors
func (c *Memory) Decr(key string) (int64, error) {
item := c.get(c.Prefix + key)
if item == nil {
item = NewItem(0, 0)
}
err := item.Decr()
if err != nil {
return 0, err
}
ttl := item.TTL
if ttl > 0 {
ttl = int64((item.Expiration - time.Now().UnixNano()) / 1e9)
}
if ttl < 0 {
return 0, fmt.Errorf("cache: expired")
}
err = c.Set(key, item.Val, ttl)
if err != nil {
return 0, err
}
return item.Val.(int64), nil
}
// Delete delete cached data by given key
func (c *Memory) Delete(key string) error {
c.mu.Lock()
defer c.mu.Unlock()
c.store.Remove(c.Prefix + key)
return nil
}
// Flush flush cacher
func (c *Memory) Flush() error {
c.mu.Lock()
defer c.mu.Unlock()
var l int
for {
l = c.store.Len()
if l > 0 {
c.store.RemoveOldest()
} else {
break
}
}
c.bytes = 0
return nil
}
// Start new a cacher and start service
func (c *Memory) Start(o Options) error {
c.Name = o.Name
c.Prefix = o.Prefix
c.bytesLimit = MemoryLimit
if o.Config != nil {
if v, ok := o.Config["bytesLimit"].(int64); ok {
c.bytesLimit = v
}
}
if c.bytesLimit < MemoryLimitMin {
c.bytesLimit = MemoryLimitMin
}
if c.store == nil {
c.store = lru.New(0)
c.store.OnEvicted = func(key lru.Key, value interface{}) {
c.bytes -= int64(len(value.(ItemBinary)))
}
}
return nil
}
// gc release memory for storage new item
// if free bytes can store item returns
// remove items until bytes less than bytesLimit - size
func (c *Memory) gc(size int64) error {
if c.bytes+size < c.bytesLimit {
return nil
}
if size > MenoryObjectMaxSize {
return fmt.Errorf("cache: object size limit to %d bytes", MenoryObjectMaxSize)
}
releaseSize := c.bytesLimit - size*2
if releaseSize <= 0 {
releaseSize = c.bytesLimit - size
}
for c.bytes > releaseSize {
if c.store.Len() > 0 {
c.store.RemoveOldest()
} else {
break
}
}
return nil
}
func init() {
Register("memory", NewMemory)
}