向ActorSystem中的所有actor发送消息

5

有没有可能向actor系统中的所有actor发送消息?我一直在查看广播路由器示例,但是这太边缘化了,我无法理解如何动态添加actor到路由器中。

我们正在使用Scala进行Akka开发。

谢谢!

2个回答

13
system.actorSelection("/user/*") ! msg

选择所有父元素的子元素并向它们发送消息。


问题是关于发送给所有的演员,而不仅仅是根节点的子代。那么关于根节点的孙子代呢? - James Moore

9

如果您想发送消息给所有动态创建的actor,可以使用eventBus

我个人在我的情况下使用系统.eventStream。

从一个actor中,您可以向所有人发送:

context.system.eventStream.publish(StatisticsMessage())

或者直接使用系统进行操作。

演员必须订阅以下内容:

context.system.eventStream.subscribe

我扩展自:

trait SubscriberActor extends Actor {

  def subscribedClasses: Seq[Class[_]]

  override def preStart() {
    super.preStart()
    subscribedClasses.foreach(this.context.system.eventStream.subscribe(this.self, _))
  }

  override def postStop() {
    subscribedClasses.foreach(this.context.system.eventStream.unsubscribe(this.self, _))
    super.postStop()
  }
}

谢谢twillouer!我也一直在考虑这个问题,但是我真的很缺乏好的例子。 - Pepster
2
  1. 可能在 postStop 中你需要 "unsubscribe"。
  2. 在调用 super.postStop() 之前取消订阅可能是一个更好的主意。
- Alexey Romanov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接