[英]How to implement simple retry using AsyncHttpClient and scala
我在我的scala項目中使用https://github.com/AsyncHttpClient/async-http-client這個庫,並使用它執行一些http調用,但是現在在某些http調用上,如果我沒有收到,我需要重試一次調用預期結果為3倍。
我應該如何執行這樣的事情?
Thaknks
這是一個基於Future.recoverWith的重試功能的示例,如果運行它,您會看到它打印“運行過程”,直到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))
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.