-
Notifications
You must be signed in to change notification settings - Fork 0
/
Map.go
108 lines (90 loc) · 1.98 KB
/
Map.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
package main
import (
"sync"
"time"
)
type KeyValueCache struct {
cache map[string]cacheEntry
maxSize int32
mutex sync.RWMutex
expiration time.Duration
}
type cacheEntry struct {
value interface{}
expireTime time.Time
}
func NewCache(MaxSize int32, expiration time.Duration) *KeyValueCache {
cache := &KeyValueCache{
cache: make(map[string]cacheEntry),
maxSize: MaxSize,
expiration: expiration,
}
go cache.startCleanupTask()
return cache
}
func (cache *KeyValueCache) put(key string, value interface{}) {
cache.mutex.Lock()
defer cache.mutex.Unlock()
if int32(len(cache.cache)) >= cache.maxSize {
cache.evict()
}
cache.cache[key] = cacheEntry{
value: value,
expireTime: time.Now().Add(cache.expiration),
}
}
func (cache *KeyValueCache) get(key string) (interface{}, bool) {
cache.mutex.RLock()
defer cache.mutex.RUnlock()
entry, found := cache.cache[key]
if !found || time.Now().After(entry.expireTime) {
if found {
delete(cache.cache, key)
}
return nil, false
}
return entry.value, true
}
func (cache *KeyValueCache) evict() {
for key := range cache.cache {
delete(cache.cache, key)
break
}
}
func (cache *KeyValueCache) remove(key string) {
cache.mutex.Lock()
defer cache.mutex.Unlock()
delete(cache.cache, key)
}
func (cache *KeyValueCache) isContain(key string) bool {
_, found := cache.cache[key]
return found
}
func (cache *KeyValueCache) update(key string, value interface{}) int8 {
if cache.isContain(key) {
cache.cache[key] = cacheEntry{
value: value,
expireTime: time.Now().Add(cache.expiration),
}
return 1
}
return -1
}
func (cache *KeyValueCache) startCleanupTask() {
ticker := time.NewTicker(cache.expiration)
defer ticker.Stop()
for {
<-ticker.C
cache.cleanup()
}
}
func (cache *KeyValueCache) cleanup() {
cache.mutex.Lock()
defer cache.mutex.Unlock()
now := time.Now()
for key, entry := range cache.cache {
if now.After(entry.expireTime) {
delete(cache.cache, key)
}
}
}