在 Akka 中为多个演员订阅 Dead Letters

Subscribing multiple actors to Dead Letters in Akka

我正在尝试创建一个包含两个参与者的简单应用程序:

这是完美运行的代码:

object Hw extends App {
  // creating Master actor
  val masterActorSystem = ActorSystem("Master")
  val master = masterActorSystem.actorOf(Props[Master], "Master")

  // creating Dead Letters listener actor
  val deadLettersActorSystem = ActorSystem.create("DeadLettersListener")
  val listener = deadLettersActorSystem.actorOf(Props[DeadLettersListener])

  // subscribe listener to Master's DeadLetters
  masterActorSystem.eventStream.subscribe(listener, classOf[DeadLetter])
  masterActorSystem.eventStream.subscribe(listener, classOf[UnhandledMessage])
}

虽然根据 akka 手册,ActorSystem 是一个很重的对象,我们应该为每个应用程序只创建一个。但是当我替换这些行时:

val deadLettersActorSystem = ActorSystem.create("DeadLettersListener")
val listener = deadLettersActorSystem.actorOf(Props[DeadLettersListener])

使用此代码:

val listener = masterActorSystem.actorOf(Props[DeadLettersListener], "DeadLettersListener")

订阅不再有效,DeadLettersListener 没有收到任何死消息或未处理消息。

你能解释一下我做错了什么,并给出在这种情况下如何订阅 Dead Letters 的建议吗?

我真的无法想象你做错了什么,我创建了一个小例子,它似乎有效:

object Hw extends App {

  class Master extends Actor {
    override def receive: Receive = {
      case a => println(s"$a received in $self")
    }
  }

  class DeadLettersListener extends Actor {
    override def receive: Actor.Receive = {
      case a => println(s"$a received in $self")
    }
  }

  // creating Master actor
  val masterActorSystem = ActorSystem("Master")
  val master = masterActorSystem.actorOf(Props[Master], "Master")
  val listener = masterActorSystem.actorOf(Props[DeadLettersListener])

  // subscribe listener to Master's DeadLetters
  masterActorSystem.eventStream.subscribe(listener, classOf[DeadLetter])
  masterActorSystem.eventStream.subscribe(listener, classOf[UnhandledMessage])

  masterActorSystem.actorSelection("/unexistingActor") ! "yo"
}

可以试试吗?