-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlocal_freecache.go
79 lines (69 loc) · 1.41 KB
/
local_freecache.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
package g2cache
import (
"github.com./coocood/freecache"
"sync"
)
var (
DefaultFreeCacheSize = 50 * 1024 * 1024 // 50MB
)
type FreeCache struct {
storage *freecache.Cache
stop chan struct{}
stopOnce sync.Once
}
func NewFreeCache() *FreeCache {
f := &FreeCache{
storage: freecache.NewCache(DefaultFreeCacheSize),
stop: make(chan struct{}, 1),
}
return f
}
func (c *FreeCache) Set(key string, e *Entry) error {
select {
case <-c.stop:
return LocalStorageClose
default:
}
s, _ := json.Marshal(e)
// local storage should set Obsolete time
obsolete := e.GetObsoleteTTL()
return c.storage.Set([]byte(key), s, int(obsolete))
}
func (c *FreeCache) Del(key string) error {
select {
case <-c.stop:
return LocalStorageClose
default:
}
c.storage.Del([]byte(key))
return nil
}
func (c *FreeCache) Get(key string, obj interface{}) (*Entry, bool, error) {
select {
case <-c.stop:
return nil, false, LocalStorageClose
default:
}
b, err := c.storage.Get([]byte(key))
if err != nil {
if err == freecache.ErrNotFound {
return nil, false, nil
}
return nil, false, err
}
e := new(Entry)
e.Value = obj // Save the reflection structure of obj
err = json.Unmarshal(b, e)
if err != nil {
return nil, false, err
}
return e, true, nil
}
func (c *FreeCache) close() {
close(c.stop)
c.storage.Clear()
}
func (c *FreeCache) Close() {
c.stopOnce.Do(c.close)
}
func (c *FreeCache) ThreadSafe() {}