-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cache.go
107 lines (88 loc) · 1.92 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
103
104
105
106
107
package gouse
import (
"errors"
"sync"
"time"
"github.com/patrickmn/go-cache"
)
/* Local cache */
type ILocalCache struct {
Set map[string]string
Lock sync.RWMutex
}
func NewLocalCache() *ILocalCache {
return &ILocalCache{
Set: make(map[string]string),
Lock: sync.RWMutex{},
}
}
func (c *ILocalCache) GetLocalCache(key string) (string, error) {
c.Lock.RLock()
defer c.Lock.RUnlock()
if c.Set == nil {
return "", errors.New("set cache is not initialized")
}
return c.Set[key], nil
}
func (c *ILocalCache) SetLocalCache(key, value string) {
c.Lock.Lock()
defer c.Lock.Unlock()
c.Set[key] = value
}
func (c *ILocalCache) DelLocalCache(key string) {
c.Lock.Lock()
defer c.Lock.Unlock()
delete(c.Set, key)
}
func (c *ILocalCache) FlushLocalCache() {
c.Lock.Lock()
defer c.Lock.Unlock()
c.Set = map[string]string{}
}
func (c *ILocalCache) AllLocalCache() map[string]string {
c.Lock.RLock()
defer c.Lock.RUnlock()
return c.Set
}
/* temp cache */
type ITmpCache struct {
Expires time.Duration
Set *cache.Cache
}
func NewTmpCache(expires ...time.Duration) *ITmpCache {
var expire time.Duration
if len(expires) > 0 {
expire = expires[0]
} else {
expire = 24 * time.Hour
}
return &ITmpCache{
Expires: expire,
Set: cache.New(expire, expire),
}
}
func (c *ITmpCache) GetTmpCache(cacheKey string) interface{} {
if val, found := c.Set.Get(cacheKey); found {
return val
}
return nil
}
func (c *ITmpCache) SetTmpCache(cacheKey string, value interface{}, expireTime time.Duration) {
if expireTime == 0 {
expireTime = cache.DefaultExpiration
}
c.Set.Set(cacheKey, value, expireTime)
}
func (c *ITmpCache) DelTmpCache(cacheKey string) {
c.Set.Delete(cacheKey)
}
func (c *ITmpCache) FlushTmpCache() {
c.Set.Flush()
}
func (c *ITmpCache) AllTmpCache() map[string]string {
result := make(map[string]string)
for k := range c.Set.Items() {
result[k] = ToString(c.GetTmpCache(k))
}
return result
}