-
Notifications
You must be signed in to change notification settings - Fork 0
/
multi.go
80 lines (72 loc) · 1.57 KB
/
multi.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
package gfcache
type MultiCache struct {
caches []Cache
}
func NewMultiCache(caches ...Cache) *MultiCache {
return &MultiCache{caches: caches}
}
func (c *MultiCache) Append(cache Cache) *MultiCache {
c.caches = append(c.caches, cache)
return c
}
func (c *MultiCache) HasCache(key string) bool {
length := len(c.caches)
if length == 0 {
return false
}
return c.caches[length-1].HasCache(key)
}
func (c *MultiCache) GetCache(key string, data interface{}) error {
length := len(c.caches)
if length == 0 {
return CacheNotFound
}
if !c.caches[length-1].HasCache(key) {
_ = c.DelCacheFromLevel(key, length-2)
return CacheNotFound
}
for i, cache := range c.caches {
if err := cache.GetCache(key, data); err == nil {
if i > 0 {
_ = c.caches[i-1].SetCache(key, data)
}
return nil
} else if err == RecordNotFound {
if i > 0 {
_ = c.caches[i-1].SetCache(key, nil)
}
return RecordNotFound
}
}
return CacheNotFound
}
func (c *MultiCache) SetCache(key string, data interface{}) error {
length := len(c.caches)
if length == 0 {
return nil
}
return c.caches[length-1].SetCache(key, data)
}
func (c *MultiCache) DelCache(key string) error {
length := len(c.caches)
if length == 0 {
return nil
}
return c.caches[length-1].DelCache(key)
}
func (c *MultiCache) DelCacheFromLevel(key string, levelIdx int) error {
if levelIdx < 0 {
return nil
}
length := len(c.caches)
if levelIdx > length-1 {
levelIdx = length - 1
}
for i := levelIdx; i >= 0; i-- {
err := c.caches[i].DelCache(key)
if err != nil {
return err
}
}
return nil
}