【问题标题】:Enable retries on the Scala function returning a Future在返回 Future 的 Scala 函数上启用重试
【发布时间】:2019-12-24 05:09:30
【问题描述】:

我有一些函数返回Futures。调用者通过onComplete 注册回调。

def makeHttpRequest(): Future[T] = ???
makeHttpRequest().onComplete {
  case Success(v) => ???
  case Failure(ex) => ???
}

现在我想对这些函数(或函数调用)启用重试。对如何实现这一点有什么建议吗?

【问题讨论】:

    标签: scala


    【解决方案1】:

    没有开箱即用的重试功能。但是基于Retry a function that returns a Future 考虑

    def retry[T](n: Int, expr: => Future[T]): Future[T] =
      Future.unit.flatMap(_ => expr).recoverWith {
        case e if n > 1 => retry(n - 1, expr)
        case e => Future.failed(e)
      }
    
    retry(3, makeHttpRequest())
    

    https://scalafiddle.io/sf/otseSX0/0

    或考虑专用库,例如​​softwaremill/retry

    【讨论】:

    • 在第一种情况下,您需要 case e if n > 1 而不是 case e if n > 0 重试 3 次而不是 4 次。
    • 如果我们想等待一段时间再做一次尝试怎么办? sleep 不是一个好选择。还有其他简单的选择吗?我正在使用 Akka/Scala,但不想将消息重新安排给演员。
    【解决方案2】:
    def makeHttpRequest(maxRetryCount: Int, currentRetryCount: Int = 0): Future[T] = {
      val responseFuture = ???
      if (currentRetryCount == maxRetryCount)
        responseFuture
      else
        responseFuture.recoverWith(makeHttpRequest(maxRetryCount, currentRetryCount + 1))
    }
    
    makeHttpRequest(3).onComplete {
      case Success(v) => ???
      case Failure(ex) => ???
    }
    

    【讨论】:

      猜你喜欢
      • 2020-03-20
      • 1970-01-01
      • 2016-06-03
      • 2017-08-02
      • 2023-03-06
      • 1970-01-01
      • 1970-01-01
      • 2022-12-09
      • 1970-01-01
      相关资源
      最近更新 更多