/
cache.go
104 lines (95 loc) · 2.06 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
/*
memory cache util
*/
package util
import (
"bytes"
"encoding/gob"
"errors"
"fmt"
cache "github.com/patrickmn/go-cache"
"sync"
"time"
)
var (
l sync.Mutex
)
// MemoryCache memory cache struct
type MemoryCache struct {
defaultHour int
cleanupInterval int
cc *cache.Cache
}
// GobEncode gob encode
func GobEncode(data interface{}) ([]byte, error) {
buf := bytes.NewBuffer(nil)
l.Lock()
defer l.Unlock()
enc := gob.NewEncoder(buf)
err := enc.Encode(data)
if err != nil {
return nil, fmt.Errorf("god encode:%v", err)
}
return buf.Bytes(), err
}
// GobDecode GobDecode
func GobDecode(data []byte, to interface{}) error {
buf := bytes.NewBuffer(data)
l.Lock()
defer l.Unlock()
dec := gob.NewDecoder(buf)
return dec.Decode(to)
}
// NewMemoryCache return a new memory cache
func NewMemoryCache(defaultHour, cleanupInterval int) *MemoryCache {
return &MemoryCache{
defaultHour: defaultHour,
cleanupInterval: cleanupInterval,
cc: cache.New(time.Duration(defaultHour)*time.Hour, time.Duration(cleanupInterval)*time.Minute),
}
}
// SetCache set cache to key and return error
func (m *MemoryCache) SetCache(key string, value interface{}) error {
if key == "" {
return errors.New("key is nil")
}
if value == nil {
return errors.New("value is nil")
}
if m.cc == nil {
return errors.New("must init memory cache first")
}
data, err := GobEncode(value)
if err != nil {
return err
}
return m.cc.Add(key, data, cache.DefaultExpiration)
}
// GetCache return cache data
func (m *MemoryCache) GetCache(key string, to interface{}) (ok bool, err error) {
if key == "" {
err = errors.New("key is nil")
return
}
if m.cc == nil {
err = errors.New("must init memory cache first")
return
}
data, ok := m.cc.Get(key)
if ok {
err = GobDecode(data.([]byte), to)
return
}
return
}
// RemoveCache delete cache
func (m *MemoryCache) RemoveCache(key string) error {
if key == "" {
return errors.New("key is nil")
}
if m.cc == nil {
return errors.New("must init memory cache first")
}
m.cc.Delete(key)
return nil
}