我希望创建一个服务,其中它向特定的URL发出HTTP请求,如果它在1秒内没有得到结果,该请求将超时,然后它将使用另一个请求重试,最多重试3次。
如何在scala中实现这一点?
我正在寻找Akka HTTP和Play的WSClient的文档,但我找不到它被提到的任何地方。
注意:在请求对服务器产生副作用的情况下,我希望不成功的请求不产生副作用。如何实现此行为?这有可能吗?
发布于 2019-01-25 19:17:57
您还可以使用akka模式中的retry:
import akka.pattern.{ask, pipe, retry}
import akka.actor.{Actor, ActorSystem, Props, Scheduler}
import akka.util.Timeout
import scala.concurrent.duration._
import scala.concurrent.{Await, ExecutionContext, Future}
class ClientActor extends Actor { //actor which times out 2 times and succeeds 3rd time
var attempts = 0
def receive = {
case "request" =>
this.attempts = attempts + 1
if (attempts < 3) {
Thread.sleep(2000)
Future.failed(new Exception("timed out")) pipeTo sender
} else {
Thread.sleep(500)
Future.successful(s"Successful in $attempts attempt") pipeTo sender
}
println(s"Attempt: $attempts")
}
}
val system = ActorSystem("system") //actor system and needed implicits
implicit val ec: ExecutionContext = system.dispatcher
implicit val timeout: Timeout = Timeout(1 seconds)
implicit val scheduler: Scheduler = system.scheduler
val client = system.actorOf(Props[ClientActor], "client-actor")
val future = retry(() => client ? "request", 3, 1 second) //create future which would retry 3 times
println(Await.result(future, 10 seconds)) //Would write "Successful in 3 attempt"发布于 2019-01-25 13:57:14
我理解你的问题,你需要做的是:
步骤
你可以在Akka Http和Akka Actors的合作下做到这一点。
通过使用Akka角色,您可以告诉您的服务在获取TimeoutException时需要做什么。您可以通过Akka ask pattern进行API调用。如果您将看到Akka ask pattern here的文档。它使用Akka ask timeout,您可以将其设置为您想要的任何值,以防您在超时时间内没有得到响应,您将获得AkkaAskTimeOutException,它将被您的孩子参与者捕获,然后它将被传递到supervisor actor,而Supervisor actor捕获异常我们可以使用Supervisor策略,并可以指定需要执行的操作(重启、关机、恢复等)。
监管策略:你可以在here上读到。实际上,下面是一个基于akka actor的应用程序的基本结构。
Supervisor Actor (我们在supervisor中编写supervisor策略),并且它有子Actor。
Child1(业务逻辑) child2 (业务逻辑)
https://stackoverflow.com/questions/54359485
复制相似问题