forked from mickael-kerjean/filestash
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cache.go
102 lines (88 loc) · 1.97 KB
/
cache.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
package common
import (
"fmt"
"github.com/mitchellh/hashstructure"
"github.com/patrickmn/go-cache"
"sync"
"time"
)
type AppCache struct {
Cache *cache.Cache
}
func (a *AppCache) Get(key interface{}) interface{} {
hash, err := hashstructure.Hash(key, nil)
if err != nil {
return nil
}
value, found := a.Cache.Get(fmt.Sprintf("%d", hash))
if !found {
return nil
}
return value
}
func (a *AppCache) Set(key map[string]string, value interface{}) {
hash, err := hashstructure.Hash(key, nil)
if err != nil {
return
}
a.Cache.Set(fmt.Sprint(hash), value, cache.DefaultExpiration)
}
func (a *AppCache) SetKey(key string, value interface{}) {
a.Cache.Set(key, value, cache.DefaultExpiration)
}
func (a *AppCache) Del(key map[string]string) {
hash, _ := hashstructure.Hash(key, nil)
a.Cache.Delete(fmt.Sprint(hash))
}
func (a *AppCache) OnEvict(fn func(string, interface{})) {
a.Cache.OnEvicted(fn)
}
func NewAppCache(arg ...time.Duration) AppCache {
var retention time.Duration = 5
var cleanup time.Duration = 10
if len(arg) > 0 {
retention = arg[0]
if len(arg) > 1 {
cleanup = arg[1]
}
}
c := AppCache{}
c.Cache = cache.New(retention*time.Minute, cleanup*time.Minute)
return c
}
func NewQuickCache(arg ...time.Duration) AppCache {
var retention time.Duration = 5
var cleanup time.Duration = 10
if len(arg) > 0 {
retention = arg[0]
if len(arg) > 1 {
cleanup = arg[1]
}
}
c := AppCache{}
c.Cache = cache.New(retention*time.Second, cleanup*time.Second)
return c
}
type KeyValueStore struct {
cache map[string]interface{}
sync.RWMutex
}
func NewKeyValueStore() KeyValueStore {
return KeyValueStore{cache: make(map[string]interface{})}
}
func (s *KeyValueStore) Get(key string) interface{} {
s.RLock()
val := s.cache[key]
s.RUnlock()
return val
}
func (s *KeyValueStore) Set(key string, value interface{}) {
s.Lock()
s.cache[key] = value
s.Unlock()
}
func (s *KeyValueStore) Clear() {
s.Lock()
s.cache = make(map[string]interface{})
s.Unlock()
}