-
Notifications
You must be signed in to change notification settings - Fork 0
/
memcache.go
199 lines (161 loc) · 3.87 KB
/
memcache.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
package memcache
import "time"
const (
LockWithKeyDefaultTimeout = 10 * time.Millisecond
)
// Get - fetch item from cache with ok indicating status of the operation
func (mc *CacheType) Get(key string) (value interface{}, ok bool) {
mc.m.RLock()
defer mc.m.RUnlock()
valueType, ok := mc.cache[key]
if ok {
value = valueType.Value
}
return
}
// GetByID - fetch item from cache based on item ID. Return nil otherwise
func (mc *CacheType) GetByID(itemID int64) (item interface{}) {
mc.m.RLock()
defer mc.m.RUnlock()
if itemID < 0 {
return nil
}
if itemID <= mc.Len() {
item = mc.items[itemID-1]
}
return
}
// Add - add item to cache and return resulting item ID
func (mc *CacheType) Add(key string, value interface{}) (itemID int64) {
if _, ok := mc.Get(key); ok {
return
}
mc.m.Lock()
defer mc.m.Unlock()
valueStruct := &ValueType{
Value: value,
Expires: 0,
MetaData: key,
}
mc.items = append(mc.items, valueStruct)
mc.cache[key] = valueStruct
return mc.Len()
}
// Set - set key/value pair without expiration
func (mc *CacheType) Set(key string, value interface{}) {
mc.SetEx(key, value, 0)
}
// SetEx - set key/value pair with expiration
func (mc *CacheType) SetEx(key string, value interface{}, expires int64) {
mc.m.Lock()
defer mc.m.Unlock()
if expires > 0 {
expires += time.Now().Unix()
}
mc.cache[key] = &ValueType{
Value: value,
Expires: expires,
}
}
// GetEx - get key/value pair with expiration
func (mc *CacheType) GetEx(key string) (*ValueType, bool) {
mc.m.RLock()
defer mc.m.RUnlock()
valueType, ok := mc.cache[key]
return valueType, ok
}
// Len - returns cache length
func (mc *CacheType) Len() (cacheSize int64) {
cacheSize = int64(len(mc.cache))
return
}
// LenSafe - same as Len() but with read lock
func (mc *CacheType) LenSafe() (cacheSize int64) {
mc.m.RLock()
defer mc.m.RUnlock()
return mc.Len()
}
// Cache - return whole cache contents
func (mc *CacheType) Cache() (cache map[string]*ValueType) {
cache = mc.cache
return
}
// UnsafeDelete - removes item from cache
func (mc *CacheType) UnsafeDelete(key string) {
delete(mc.cache, key)
idx := 0
for valuePos, value := range mc.items {
if value.MetaData == key {
idx = valuePos
break
}
}
// I should really really test this :) - SliceTricks
if idx < len(mc.items)-1 {
copy(mc.items[idx:], mc.items[idx+1:])
}
if len(mc.items) >= 1 {
mc.items[len(mc.items)-1] = nil
mc.items = mc.items[:len(mc.items)-1]
}
}
// Delete - removes item from cache
func (mc *CacheType) Delete(key string) {
mc.m.Lock()
defer mc.m.Unlock()
mc.UnsafeDelete(key)
}
// Evictor - background goroutine that periodically purges expired keys
func (mc *CacheType) Evictor() {
for {
select {
case <-mc.done:
return
case <-mc.ticker.C:
mc.m.Lock()
for key, value := range mc.cache {
if value.Expires == 0 {
continue
}
if value.Expires-time.Now().Unix() <= 0 {
mc.logger.Printf("Evicting %s\n", key)
mc.UnsafeDelete(key)
}
}
mc.m.Unlock()
}
}
}
// Stop - run some cleaning chores during shutdown
func (mc *CacheType) Stop() {
mc.ticker.Stop()
mc.done <- struct{}{}
mc.logger.Debug("Memcache is saying goodbye!")
}
func (mc *CacheType) SetLockWithKeyTimeout(timeout time.Duration) {
mc.lockWithKeyTimeout = timeout
}
func (mc *CacheType) LockWithKey(key string) {
for {
if _, ok := mc.Get(key); !ok {
mc.Set(key, struct{}{})
break
} else {
time.Sleep(mc.lockWithKeyTimeout)
}
}
}
func (mc *CacheType) UnlockWithKey(key string) {
mc.Delete(key)
}
// New - prepare and populate memcache instance
func New(logger Logger) (memCache *CacheType) {
memCache = &CacheType{cache: make(map[string]*ValueType),
done: make(chan struct{}),
ticker: time.NewTicker(1 * time.Second),
logger: logger,
lockWithKeyTimeout: LockWithKeyDefaultTimeout,
}
go memCache.Evictor()
return
}