How to implement simple retry using AsyncHttpClient and scala

时间:2017-07-12 08:02:22

标签: java scala http

Im using https://github.com/AsyncHttpClient/async-http-client this library in my scala project, and im performing some http calls with it, but now on some http calls I need to retry a call if I dont get my expected result for 3 times.

How should I implement something like this?

thaknks

1 个答案:

答案 0 :(得分:0)

This is an example of retry function based on Future.recoverWith If you run it you can see that it prints "run process" until the Future is successful but not more than 'times' 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))

}