-
Notifications
You must be signed in to change notification settings - Fork 2
/
shard.go
118 lines (105 loc) · 2.27 KB
/
shard.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
package cache
import (
"sync"
"time"
)
// ExpiredCallback Callback the function when the key-value pair expires
// Note that it is executed after expiration
type ExpiredCallback func(k string, v interface{}) error
type memCacheShard struct {
hashmap map[string]Item
lock sync.RWMutex
expiredCallback ExpiredCallback
}
func newMemCacheShard(conf *Config) *memCacheShard {
return &memCacheShard{expiredCallback: conf.expiredCallback, hashmap: map[string]Item{}}
}
func (c *memCacheShard) set(k string, item *Item) {
c.lock.Lock()
c.hashmap[k] = *item
c.lock.Unlock()
return
}
func (c *memCacheShard) get(k string) (interface{}, bool) {
c.lock.RLock()
item, exist := c.hashmap[k]
c.lock.RUnlock()
if !exist {
return nil, false
}
if !item.Expired() {
return item.v, true
}
if c.delExpired(k) {
return nil, false
}
return c.get(k)
}
func (c *memCacheShard) getSet(k string, item *Item) (interface{}, bool) {
defer c.set(k, item)
return c.get(k)
}
func (c *memCacheShard) getDel(k string) (interface{}, bool) {
defer c.del(k)
return c.get(k)
}
func (c *memCacheShard) del(k string) int {
var count int
c.lock.Lock()
v, found := c.hashmap[k]
if found {
delete(c.hashmap, k)
if !v.Expired() {
count++
}
}
c.lock.Unlock()
return count
}
//delExpired Only delete when key expires
func (c *memCacheShard) delExpired(k string) bool {
c.lock.Lock()
item, found := c.hashmap[k]
if !found || !item.Expired() {
c.lock.Unlock()
return false
}
delete(c.hashmap, k)
c.lock.Unlock()
if c.expiredCallback != nil {
_ = c.expiredCallback(k, item.v)
}
return true
}
func (c *memCacheShard) ttl(k string) (time.Duration, bool) {
c.lock.RLock()
v, found := c.hashmap[k]
c.lock.RUnlock()
if !found || !v.CanExpire() || v.Expired() {
return 0, false
}
return v.expire.Sub(time.Now()), true
}
func (c *memCacheShard) checkExpire() {
var expiredKeys []string
c.lock.RLock()
for k, item := range c.hashmap {
if item.Expired() {
expiredKeys = append(expiredKeys, k)
}
}
c.lock.RUnlock()
for _, k := range expiredKeys {
c.delExpired(k)
}
}
func (c *memCacheShard) saveToMap(target map[string]interface{}) {
c.lock.RLock()
for k, item := range c.hashmap {
if item.Expired() {
continue
}
target[k] = item.v
}
c.lock.RUnlock()
}