我正在尝试创建一个包含两个actor的简单应用程序:
以下是完美运作的代码:
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或Unhandled消息。
您能否解释一下我做错了什么,并在这种情况下给出如何订阅Dead Letters的建议?
答案 0 :(得分:2)
我无法想象你做错了什么,我创造了一个小例子,它似乎有效:
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"
}
你能尝试吗?