4

有没有什么简单的方法可以重复请求,直到在 Play2.1(scala)中获得成功结果?以及如何限制尝试次数?

我想做这样的事情:

WS.url("some.url").get().map{ response =>
  val strval = someFunction(response)
  strval match {
    case "success" => println("do something after successful request")
    case "error" => println("repeat same request until success - and repeat maximum N times!")
  }
}

提前致谢!

4

2 回答 2

3

尝试这个:

def wSCall = WS.url("http://foo/bar").get()

def ƒ(response: Response, n: Int): Result = {
  val strval = someFunction(response)

  strval match {
    case "success" => Ok("Ok!")
    case "error"   => {
      if (n > 0)
        Async { wSCall.map(response => ƒ(response, n - 1)) }
      else
        BadRequest("Fail :(")
    }
  }
}

Async { wSCall.map(response => ƒ(response, 10)) }
于 2013-04-13T11:34:33.373 回答
3

未经测试

你可以这样做:

import scala.concurrent._
import play.api.libs.concurrent.Execution.Implicits._

def withRetry[T](retries:Int = 5)(f: => Future[T]) = 
  f.recoverWith {
    case t:Throwable if (retries > 0) => withRetry(retries - 1)(f)
  }

然后在您自己的代码中,您可以像这样使用它:

withRetry(retries = 2) {
  WS.url("some.url").get
    .map { response =>
      require(someFunction(response) != "error", "Please retry")
      response
    }
}

如果您愿意将其重写someFunction为 a Response => Boolean,您可以像这样使用它:

def someFunction(r: Response): Boolean = ???

withRetry(retries = 2) {
  WS.url("some.url").get
    .filter(someFunction)
}
于 2013-04-13T08:44:29.433 回答