-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsingleflight_proxy.go
46 lines (36 loc) · 1.2 KB
/
singleflight_proxy.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
package cache_proxy_demo
import (
"golang.org/x/sync/singleflight"
)
func UseSingleflight(baseProxy *BaseCacheProxy) CacheProxy {
return &SingleflightProxy{
transform: baseProxy.Transform,
cache: baseProxy.Cache,
baseProxy: baseProxy,
}
}
type SingleflightProxy struct {
transform TransformQryOptionToCacheKey
cache Cache
// Group.Do(key string, fn func() (interface{}, error)) (v interface{}, err error, shared bool)
workflow singleflight.Group
baseProxy *BaseCacheProxy
}
func (proxy *SingleflightProxy) Execute(qryOption any, readModelType any) (readModel any, err error) {
return proxy.execute1(qryOption, readModelType)
}
func (proxy *SingleflightProxy) execute1(qryOption any, readModelType any) (readModel any, err error) {
key := proxy.transform(qryOption)
readModel, err, _ = proxy.workflow.Do(key, func() (interface{}, error) {
return proxy.baseProxy.Execute(qryOption, readModelType)
})
return
}
func (proxy *SingleflightProxy) execute3(qryOption any, readModelType any) (readModel any, err error) {
key := proxy.transform(qryOption)
val, err := proxy.cache.GetValue(key, readModelType)
if err == nil {
return val, nil
}
return proxy.execute1(qryOption, readModelType)
}