You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
go-zero/core/fx/retry.go

47 lines
888 B
Go

4 years ago
package fx
import "github.com/tal-tech/go-zero/core/errorx"
4 years ago
const defaultRetryTimes = 3
type (
// RetryOption defines the method to customize DoWithRetry.
4 years ago
RetryOption func(*retryOptions)
retryOptions struct {
times int
}
)
// DoWithRetry runs fn, and retries if failed. Default to retry 3 times.
func DoWithRetry(fn func() error, opts ...RetryOption) error {
4 years ago
var options = newRetryOptions()
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()
}
// WithRetry customize a DoWithRetry call with given retry times.
func WithRetry(times int) RetryOption {
4 years ago
return func(options *retryOptions) {
options.times = times
}
}
func newRetryOptions() *retryOptions {
return &retryOptions{
times: defaultRetryTimes,
}
}