-
Notifications
You must be signed in to change notification settings - Fork 1
/
cache.go
77 lines (66 loc) · 1.2 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
package redissvc
import (
"reflect"
"strconv"
"time"
"github.com/ahl5esoft/lite-go/contract"
)
type cache struct {
redis contract.IRedis
updateOn int64
value reflect.Value
redisKey string
loadFunc func() (interface{}, error)
}
func (m *cache) Flush() error {
_, err := m.redis.HSet(
"cache",
m.redisKey,
strconv.FormatInt(
time.Now().UnixNano(),
10,
),
)
return err
}
func (m *cache) Get(k string, v interface{}) error {
cacheOnStr, err := m.redis.HGet("cache", m.redisKey)
if err != nil {
return err
}
cacheOn, err := strconv.ParseInt(cacheOnStr, 10, 64)
if err != nil {
return err
}
if m.updateOn != cacheOn {
m.updateOn = cacheOn
res, err := m.loadFunc()
if err != nil {
return err
}
m.value = reflect.ValueOf(res)
}
rv := m.value.MapIndex(
reflect.ValueOf(k),
)
if rv.IsValid() {
reflect.ValueOf(v).Elem().Set(rv)
}
return nil
}
func (m *cache) GetUpdateOn() int64 {
return m.updateOn
}
// 创建redis缓存
func NewCache(
redis contract.IRedis,
redisKey string,
loadFunc func() (interface{}, error),
) contract.ICache {
return &cache{
redis: redis,
redisKey: redisKey,
loadFunc: loadFunc,
updateOn: time.Now().UnixNano(),
}
}