-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathasync_pool.go
78 lines (64 loc) · 1.33 KB
/
async_pool.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
package beanq
import (
"context"
"time"
"github.com/panjf2000/ants/v2"
"github.com/pkg/errors"
"github.com/retail-ai-inc/beanq/v3/helper/logger"
)
type asyncPool struct {
pool *ants.Pool
captureException func(ctx context.Context, err any)
}
func newAsyncPool(poolSize int) *asyncPool {
var (
pool *ants.Pool
err error
)
if poolSize < 0 {
pool, err = ants.NewPool(-1)
} else {
pool, err = ants.NewPool(
poolSize,
ants.WithPreAlloc(true))
}
if err != nil {
logger.New().With("", err).Panic("goroutine pool error")
}
return &asyncPool{
pool: pool,
captureException: defaultCaptureException,
}
}
func (a *asyncPool) Execute(ctx context.Context, fn func(c context.Context) error, durations ...time.Duration) {
var (
cancel context.CancelFunc
)
if len(durations) > 0 {
ctx, cancel = context.WithTimeout(ctx, durations[0])
defer cancel()
}
err := a.pool.Submit(func() {
defer func() {
if err := recover(); err != nil {
a.captureException(ctx, err)
}
}()
e := fn(ctx)
if e != nil {
a.captureException(ctx, e)
}
})
if err != nil {
a.captureException(ctx, errors.WithStack(err))
}
}
func (a *asyncPool) Release() {
a.pool.Release()
}
var defaultCaptureException = func(ctx context.Context, err any) {
if err == nil {
return
}
logger.New().Error(err)
}