go-zero/core/fx/retry.go

47 lines
886 B
Go
Raw Normal View History

2020-07-26 17:09:05 +08:00
package fx
import "github.com/zeromicro/go-zero/core/errorx"
2020-07-26 17:09:05 +08:00
const defaultRetryTimes = 3
type (
2021-02-19 17:49:39 +08:00
// RetryOption defines the method to customize DoWithRetry.
2020-07-26 17:09:05 +08:00
RetryOption func(*retryOptions)
retryOptions struct {
times int
}
)
2021-02-19 17:49:39 +08:00
// DoWithRetry runs fn, and retries if failed. Default to retry 3 times.
func DoWithRetry(fn func() error, opts ...RetryOption) error {
2021-04-15 19:49:17 +08:00
options := newRetryOptions()
2020-07-26 17:09:05 +08:00
for _, opt := range opts {
opt(options)
}
var berr errorx.BatchError
for i := 0; i < options.times; i++ {
if err := fn(); err != nil {
berr.Add(err)
} else {
return nil
}
}
return berr.Err()
}
2021-02-19 17:49:39 +08:00
// WithRetry customize a DoWithRetry call with given retry times.
func WithRetry(times int) RetryOption {
2020-07-26 17:09:05 +08:00
return func(options *retryOptions) {
options.times = times
}
}
func newRetryOptions() *retryOptions {
return &retryOptions{
times: defaultRetryTimes,
}
}