java - 如何使用 AsyncHttpClient 和 scala 实现简单的重试

标签 java scala http

我正在使用 https://github.com/AsyncHttpClient/async-http-client这个库在我的 scala 项目中,我用它执行了一些 http 调用,但是现在在一些 http 调用上,如果我 3 次没有得到预期的结果,我需要重试调用。

我应该如何实现这样的东西?

谢谢

最佳答案

这是一个基于Future.recoverWith的重试函数的例子 如果你运行它,你可以看到它会打印“run process”,直到 Future 成功但不超过“times”次

object X extends App{
  type Request = String
  type Response = String
  import scala.concurrent.ExecutionContext.Implicits.global
  def retry(request: Request, process: Request => Future[Response], times: Int): Future[Response] ={
    val responseF = process(request)
    if(times > 0)
      responseF.recoverWith{
        case ex => println("fail")
          retry(request, process, times - 1)
      }
    else
      responseF
  }

  def process(s: Request): Future[Response] = {
    println("run process")
    if(Random.nextBoolean()) Future.successful("good") else Future.failed(new Exception)
  }

  val result = retry("", process, 3)
  import scala.concurrent.duration._
  println(Await.result(result, 1.second))

}

关于java - 如何使用 AsyncHttpClient 和 scala 实现简单的重试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45051826/

相关文章:

java - hashmap和多个txt文件java

java - 为什么整数的java除法比黑客的喜悦实现更快

java - 编译和运行 Java 控制台应用程序 OS X 终端时出现问题

php - 从具有 localhost 的主机访问 Vagrant 机器上的 symfony web 服务器

http - 将 HTTP 响应与其相应的 HTTP 流水线请求相匹配

java - onManagerConnected 状态返回值 2 [市场错误]

java - 使用 Java OutputFormat 发出 Scala 元组

scala - 使用 Slick 创建单列表

scala - 如何使用shapeless在scala中实现[x] -> x?

delphi - 在 delphi 上使用 WININET 上传文件