retry.go 885 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package fx
  2. import "github.com/tal-tech/go-zero/core/errorx"
  3. const defaultRetryTimes = 3
  4. type (
  5. // RetryOption defines the method to customize DoWithRetry.
  6. RetryOption func(*retryOptions)
  7. retryOptions struct {
  8. times int
  9. }
  10. )
  11. // DoWithRetry runs fn, and retries if failed. Default to retry 3 times.
  12. func DoWithRetry(fn func() error, opts ...RetryOption) error {
  13. options := newRetryOptions()
  14. for _, opt := range opts {
  15. opt(options)
  16. }
  17. var berr errorx.BatchError
  18. for i := 0; i < options.times; i++ {
  19. if err := fn(); err != nil {
  20. berr.Add(err)
  21. } else {
  22. return nil
  23. }
  24. }
  25. return berr.Err()
  26. }
  27. // WithRetry customize a DoWithRetry call with given retry times.
  28. func WithRetry(times int) RetryOption {
  29. return func(options *retryOptions) {
  30. options.times = times
  31. }
  32. }
  33. func newRetryOptions() *retryOptions {
  34. return &retryOptions{
  35. times: defaultRetryTimes,
  36. }
  37. }