This repository has been archived by the owner on Jun 14, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
memory.go
117 lines (94 loc) · 1.98 KB
/
memory.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
package memadapter
import (
"fmt"
"sync"
"time"
"github.com/JohannesKaufmann/dynamodb-cache"
)
type item struct {
value []byte
expire time.Time
}
func (i item) isExpired(now time.Time) bool {
return now.After(i.expire)
}
type Adapter struct {
values map[string]*item
m sync.RWMutex
ttl time.Duration
renewOnRead bool
}
// -> https://stackoverflow.com/a/25487392
const NoExpiration time.Duration = -1
const CleanupInterval = time.Second * 2
func New(ttl time.Duration, renewOnRead bool) cache.InitAdapter {
return func() (cache.Adapter, error) {
i := &Adapter{
values: make(map[string]*item),
ttl: ttl,
renewOnRead: renewOnRead,
}
if ttl != NoExpiration {
go func() {
ticker := time.NewTicker(CleanupInterval)
for {
select {
case time := <-ticker.C:
i.deleteExpired(time)
// case <-i.stop:
// ticker.Stop()
// return
}
}
}()
}
return i, nil
}
}
// func NewWithRenew(ttl time.Duration)cache.InitAdapter {
// return func() (cache.Adapter, error) {
// return nil,nil
// }
// }
func (a Adapter) deleteExpired(now time.Time) {
a.m.Lock()
for key, v := range a.values {
if v.isExpired(now) {
// if now.After(v.expire) {
fmt.Println("cleanup: DELETE", key)
delete(a.values, key)
} else {
// fmt.Println("cleanup: DONT DELETE")
}
}
a.m.Unlock()
}
func (a Adapter) Get(key string) ([]byte, error) {
a.m.RLock()
defer a.m.RUnlock()
if it, ok := a.values[key]; ok {
if a.ttl != NoExpiration && it.isExpired(time.Now()) {
return nil, cache.ErrExpired
}
if a.renewOnRead {
it.expire = time.Now().Add(a.ttl)
}
return it.value, nil
}
return nil, cache.ErrNotFound
}
func (a Adapter) Set(key string, data []byte) error {
a.m.Lock()
defer a.m.Unlock()
a.values[key] = &item{
value: data,
expire: time.Now().Add(a.ttl),
}
return nil
}
func (a Adapter) Del(key string) error {
a.m.Lock()
defer a.m.Unlock()
delete(a.values, key)
return nil
}