首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使用AsyncHttpClient和scala实现简单重试

如何使用AsyncHttpClient和scala实现简单重试
EN

Stack Overflow用户
提问于 2017-07-12 16:02:22
回答 1查看 732关注 0票数 1

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

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

心得

EN

回答 1

Stack Overflow用户

发布于 2017-07-12 16:20:19

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

代码语言:javascript
运行
复制
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))

}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45051826

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档