我发现了同事写的retry函数真的好优雅

写在前面:偶然发现了一段关于retry函数的优雅实现方法的代码,读下来觉得有许多值得学习的地方,特此记录下来。

retry函数简介

retry函数在日常的研发中用到的频率特别高,特别是连接kube-apiservert进行k8s资源的增删改查时,常常会因为网络等各种各样的问题而操作失败,因此我们一般都会在限定时间内进行限定次数的重试操作(比如15s内重试3次,每5s重试一次)。

通常我们的做法是考虑封装一个retry函数,用来执行重试操作。

如下所示:

  • 我们封装一个函数类型的结构体ExecutionFunc,用来作为我们retry函数的参数。
  • 在retry函数内部,我们调用"k8s.io/apimachinery/pkg/util/wait"的ConditionFunc函数,该函数的作用解释如下ConditionFunc returns true if the condition is satisfied, or an error if the loop should be aborted.我们在其设定退出的条件为execFunc执行成功或者重试次数达到3次,这样子可以避免一直处于重试状态。
// ExecutionFunc defines the execution function
type ExecutionFunc func() (err error)

// ExecuteFuncWithRetry will exec given function with retry
func ExecuteFuncWithRetry(execFunc ExecutionFunc) error {
   
   if execFunc == nil {
   
      return errors.New("execution func can't be nil")
   }

   var lastErr error
   retryCount, execFuncName := 0, runtime.FuncForPC(reflect.ValueOf(execFunc).Pointer()).Name()
   wrapConditionFunc := wait.ConditionFunc(func() (done bool, err error) {
   
      if retryCount >= constant.DefaultMaxRetries {
   
         return true, fmt.Errorf("failed to execFunc func %s after %d retries", execFuncName, constant.DefaultMaxRetries)
      }

      if err := execFunc(); err != nil {
   
         log.WithError(err).Error(fmt.Sprintf("failed to execFunc func %s", execFuncName))
         lastErr = err
         if apierrors.IsNotFound(err) || apierrors.IsAlreadyExists(err) || apierrors.IsConflict(err) {
   
            return true, err
         }
         retryCount++
         return false
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值