我正在使用 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/