-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmemorycache.go
163 lines (113 loc) · 2.36 KB
/
memorycache.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
package memorycache
import (
"errors"
"sync"
"time"
)
// Cache struct cache
type Cache struct {
sync.RWMutex
items map[string]Item
defaultExpiration time.Duration
cleanupInterval time.Duration
}
// Item struct cache item
type Item struct {
Value interface{}
Expiration int64
Created time.Time
}
// New. Initializing a new memory cache
func New(defaultExpiration, cleanupInterval time.Duration) *Cache {
items := make(map[string]Item)
// cache item
cache := Cache{
items: items,
defaultExpiration: defaultExpiration,
cleanupInterval: cleanupInterval,
}
if cleanupInterval > 0 {
cache.StartGC()
}
return &cache
}
// Set setting a cache by key
func (c *Cache) Set(key string, value interface{}, duration time.Duration) {
var expiration int64
if duration == 0 {
duration = c.defaultExpiration
}
if duration > 0 {
expiration = time.Now().Add(duration).UnixNano()
}
c.Lock()
defer c.Unlock()
c.items[key] = Item{
Value: value,
Expiration: expiration,
Created: time.Now(),
}
}
// Get getting a cache by key
func (c *Cache) Get(key string) (interface{}, bool) {
c.RLock()
defer c.RUnlock()
item, found := c.items[key]
// cache not found
if !found {
return nil, false
}
if item.Expiration > 0 {
// cache expired
if time.Now().UnixNano() > item.Expiration {
return nil, false
}
}
return item.Value, true
}
// Delete cache by key
// Return false if key not found
func (c *Cache) Delete(key string) error {
c.Lock()
defer c.Unlock()
if _, found := c.items[key]; !found {
return errors.New("Key not found")
}
delete(c.items, key)
return nil
}
// StartGC start Garbage Collection
func (c *Cache) StartGC() {
go c.GC()
}
// GC Garbage Collection
func (c *Cache) GC() {
for {
<-time.After(c.cleanupInterval)
if c.items == nil {
return
}
if keys := c.expiredKeys(); len(keys) != 0 {
c.clearItems(keys)
}
}
}
// expiredKeys returns key list which are expired.
func (c *Cache) expiredKeys() (keys []string) {
c.RLock()
defer c.RUnlock()
for k, i := range c.items {
if time.Now().UnixNano() > i.Expiration && i.Expiration > 0 {
keys = append(keys, k)
}
}
return
}
// clearItems removes all the items which key in keys.
func (c *Cache) clearItems(keys []string) {
c.Lock()
defer c.Unlock()
for _, k := range keys {
delete(c.items, k)
}
}