为什么我没有收到 Ask 超时异常?

Why i'm not getting Ask timeout exception?

我有 2 个演员,一个监督和一个 child 演员。

主管:

class DemoActorSupervisor(implicit val system: ActorSystem, config: Config) extends Actor {

  val childActor: ActorRef = context.actorOf(FromConfig.props(Props[DemoActorChild]), "DemoChildActor")

  context.watch(childActor)

  override def receive: Receive = {
    case s: String =>
      childActor forward s
  }
}

Child演员:

class DemoActorChild extends Actor {
  def receive: Receive = {
    case s: String =>
      Thread.sleep(100)
      Future.successful(true) pipeTo (sender)
  }
}

主要方法:

object ABC extends App {
  implicit val system: ActorSystem = ActorSystem("Demo")

  implicit val config: Config = ConfigFactory.load()

  implicit val timeout: Timeout = Timeout(5, TimeUnit.MILLISECONDS)

  val supervisor = system.actorOf(DemoActorSupervisor.props(), "DemoSupervisor")

  val x: Future[Boolean] = (supervisor ? ("ASK")).mapTo[Boolean]
  x.foreach(println)
}

我已将询问超时设置为 5 英里秒,并向主管演员发出询问呼叫。它将消息转发给 child 参与者。在 child 演员中,我已将 Thread.sleep(100) 逻辑上我应该得到请求超时异常,因为我已将超时设置为 5 mili 秒并且 child 需要超过 100 mili 秒来响应,但我没有收到询问超时异常。 有人可以告诉我代码有什么问题吗?如何获得询问超时异常。

下一步试试:

x.onComplete {
    case Success(v) =>
      println(v)
    case Failure(v) =>
      println(v)
}

Future foreach只处理成功案例,akka.pattern.AskTimeoutException:属于Failure,需要自己代码处理。

或者下一个也可以:

x.foreach(println)
x.failed.foreach(println)

Future.foreach的描述中可以看到:

Asynchronously processes the value in the future once the value becomes available.

WARNING: Will not be called if this future is never completed or if it is completed with a failure.

如果你想使用Future.foreach,你应该这样写:

x.map(Success(_)).recover({case exception => Failure(exception)}).foreach(println)