我正在我的scala项目中使用https://github.com/AsyncHttpClient/async-http-client这个库,并使用它执行一些http调用,但现在在一些http调用中,如果我三次都得不到预期的结果,我需要重试调用。
我应该如何实现这样的东西呢?
心得
发布于 2017-07-12 16:20:19
这是一个基于Future.recoverWith的重试函数的例子。如果你运行它,你会看到它会打印"run process“直到将来成功,但不会超过' 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))
}https://stackoverflow.com/questions/45051826
复制相似问题