/
cache.go
91 lines (72 loc) · 1.48 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
package utils
import (
"context"
"fmt"
"sync"
)
type CacheManager struct {
sync.Pool
cacheChains GetDataChain
}
func NewCacheManager() *CacheManager {
cm := &CacheManager{}
cm.New = func() interface{} {
return &CacheRequest{}
}
return cm
}
//context.WithValue(ctx, userKey, u)
//u, ok := ctx.Value(userKey).(*User)
func (cm *CacheManager) GetData(ctx context.Context, key interface{}) interface{} {
c := cm.Get().(*CacheRequest)
c.reset()
c.ctx = ctx
c.key = key
c.cacheChains = cm.cacheChains
c.Next()
dat, _ := c.GetData()
cm.Put(c)
return dat
}
// 注意按添加的顺序依次执行
func (cm *CacheManager) AddChains(chains ...GetData) {
cm.cacheChains = append(cm.cacheChains, chains...)
}
type GetData func(*CacheRequest)
type GetDataChain []GetData
type CacheRequest struct {
index int8
cacheChains GetDataChain
key interface{}
data interface{}
isSet bool
ctx context.Context
}
func (c *CacheRequest) reset() {
c.index = -1
c.cacheChains = nil
c.key = ""
c.data = ""
c.isSet = false
}
func (c *CacheRequest) GetKey() interface{} {
return c.key
}
func (c *CacheRequest) GetData() (interface{}, bool) {
return c.data, c.isSet
}
func (c *CacheRequest) SetData(data interface{}) {
c.data = data
c.isSet = true
}
func (c *CacheRequest) Next() {
c.index++
s := int8(len(c.cacheChains))
for ; c.index < s; c.index++ {
fmt.Println("index~~~~~~", c.index)
c.cacheChains[c.index](c)
}
}
func (c *CacheRequest) Abort() {
c.index = abortIndex
}