-
Notifications
You must be signed in to change notification settings - Fork 0
/
group.go
65 lines (57 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
// Package core @Author Bing
// @Date 2023/10/24 11:07:00
// @Desc global cache group for get cache callback cache
package core
import "sync"
type callback func(k string) (any, bool)
type Group struct {
lock sync.RWMutex
Groups map[string]*Group
callback callback
lru *Lru[string, any]
}
var lock sync.RWMutex
const ()
func NewGroup(size int, name string, f callback) *Group {
defer lock.Unlock()
lock.Lock()
if f == nil {
panic("nil callback")
}
group := &Group{
Groups: make(map[string]*Group),
callback: f,
lru: NewLru[string, any](size),
}
group.Groups[name] = group
return group
}
func (g *Group) GetGroup(name string) (*Group, bool) {
defer g.lock.RUnlock()
g.lock.RLock()
group, ok := g.Groups[name]
return group, ok
}
func (g *Group) SetGroup(size int, name string, f callback) (*Group, bool) {
defer g.lock.RUnlock()
g.lock.RLock()
group := NewGroup(size, name, f)
g.Groups[name] = group
return group, true
}
func (g *Group) Get(k string) (any, bool) {
defer g.lock.RUnlock()
g.lock.RLock()
v, ok := g.lru.Get(k)
if ok {
return v, ok
}
return g.load(k)
}
func (g *Group) load(k string) (any, bool) {
v, ok := g.callback(k)
if ok {
g.lru.Add(k, v)
}
return v, ok
}