是否有任何简单的方法来重复请求,直到在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!")
}
}
提前感谢!
试试这个:
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)) }
未经测试
你可以这样做:
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
重写为Response => Boolean
,您可以这样使用:
def someFunction(r: Response): Boolean = ???
withRetry(retries = 2) {
WS.url("some.url").get
.filter(someFunction)
}