首页 > 解决方案 > Akka 演员的输出不如预期

问题描述

akka 文档之后,例如在“演员生命周期”部分中,对我来说,输出没有记录在案。我得到的是:

刚开始

第二次开始

第二停

代码是:

object StartStopActorMain extends App {
  val first = ActorSystem(StartStopActor1(), "firstActor")
  first ! "stop"
}

object StartStopActor1 {
  def apply() =
      Behaviors.setup(context => new StartStopActor1(context))
}

class StartStopActor1(context: ActorContext[String]) extends 
      AbstractBehavior[String](context) {
    println("first started")
    context.spawn(StartStopActor2(), "second")

    override def onMessage(msg: String): Behavior[String] =
        msg match {
          case "stop" => Behaviors.stopped
    }

    override def onSignal: PartialFunction[Signal, Behavior[String]] = {
        case PostStop =>
         println("first stopped")
         this
    }
}

object StartStopActor2 {

  def apply() =
      Behaviors.setup(context => new StartStopActor2(context))

 }

class StartStopActor2(context: ActorContext[String]) extends 
        AbstractBehavior[String](context) {
     println("second started")

    override def onMessage(msg: String): Behavior[String] = Behaviors.unhandled

   override def onSignal: PartialFunction[Signal, Behavior[String]] = {
         case PostStop =>
           println("second stopped")
           this
    }
}

我在这里缺少什么吗?我从那里复制了代码。

标签: akka

解决方案


以您提供的信息量,无法回答您的问题。但我最好的猜测是,您的 JVM 在第一个参与者更改以打印其停止消息之前退出。

编辑

也可能是 Akka 文档是错误的:第一个 Actor 将其行为替换为Behaviors.stopped,因此 PostStop 信号不会传递给 StartStopActor1 行为,而是传递给停止的行为。我记得几年前以这种方式实现它,理由是当参与者自愿终止时不需要 PostStop 挂钩:您想要为 PostStop 运行的任何代码也可以在返回之前运行Behaviors.stopped


推荐阅读