-
Notifications
You must be signed in to change notification settings - Fork 0
/
singleflight.go
73 lines (57 loc) · 1.21 KB
/
singleflight.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
package do
import (
"fmt"
"sync"
)
var (
singleFlightMap = NewMap[string, *singleFlight]()
// 应该是一个key对应一个wg,不能全局共用一个wg
wgMap = NewMap[string, *sync.WaitGroup]()
)
type singleFlight struct {
val any
err error
}
type SingleFlightCall[R any] func() (R, error)
// SingleFlight make sure only one request is doing with one key
func SingleFlight[R any](key string, fn SingleFlightCall[R]) (r R, err error) {
wg := initWg(key)
// 已经有请求在执行时等待其结果返回
if c, ok := singleFlightMap.Lookup(key); ok {
wg.Wait()
removeWg(key)
return c.val.(R), c.err
}
// 执行
c := &singleFlight{}
wg.Add(1)
singleFlightMap.Insert(key, c)
func() {
defer func() {
if v := recover(); v != nil {
c.err = fmt.Errorf("single flight run err: %v", v)
}
wg.Done()
}()
r, err := fn()
c.val, c.err = r, err
}()
return c.val.(R), c.err
}
func ForgotKey(key string) {
singleFlightMap.Remove(key)
removeWg(key)
}
func initWg(key string) *sync.WaitGroup {
var wg *sync.WaitGroup
if v, ok := wgMap.Lookup(key); ok {
wg = v
} else {
wg = new(sync.WaitGroup)
wgMap.Insert(key, wg)
}
return wg
}
func removeWg(key string) {
wgMap.Remove(key)
}