-
Notifications
You must be signed in to change notification settings - Fork 0
/
group.go
66 lines (54 loc) · 1.21 KB
/
group.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
package gee_cache
import "sync"
type Getter interface {
Get(key string) ([]byte, error)
}
type GetterFunc func(key string) ([]byte, error)
func (getFunc GetterFunc) Get(key string) ([]byte, error) {
return getFunc(key)
}
var (
rw sync.RWMutex
groups = make(map[string]*Group, 0)
)
func NewGroup(name string, maxBytes int64, getter Getter) *Group {
group := new(Group)
group.name = name
group.getter = getter
group.current = NewCache(maxBytes)
rw.Lock()
defer rw.Unlock()
groups[name] = group
return group
}
func GetGroup(name string) *Group {
rw.RLock()
defer rw.RUnlock()
return groups[name]
}
type Group struct {
name string
current *Cache
getter Getter
}
// 先从current获取
// 如果获取失败则调用getter获取
// 获取到了需要跟更新到current
func (group *Group) Get(key string) (ByteView, error) {
if v, ok := group.current.Get(key); ok {
return v, nil
}
return group.load(key)
}
func (group *Group) load(key string) (ByteView, error) {
return group.loadLocally(key)
}
func (group *Group) loadLocally(key string) (ByteView, error) {
v, err := group.getter.Get(key)
if err != nil {
return ByteView{}, err
}
bv := ByteView{v}
group.current.Set(key, bv)
return bv, nil
}