繁体   English   中英

如何使用AsyncHttpClient和Scala实现简单的重试

[英]How to implement simple retry using AsyncHttpClient and scala

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

我应该如何执行这样的事情?

Thaknks

这是一个基于Future.recoverWith的重试功能的示例,如果运行它,您会看到它打印“运行过程”,直到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))

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM