向ActorSystem中的所有actor发送消息

Pep*_*ter 5 scala akka

是否可以向演员系统中的所有演员发送消息?我一直在看广播路由器的例子,但是这太边缘了,我无法理解我是如何动态地将actor添加到路由器的.

我们正在使用scala for akka.

谢谢!

agi*_*eel 12

system.actorSelection("/user/*") ! msg
Run Code Online (Sandbox Code Playgroud)

选择监护人的所有孩子并向他们发送消息.


twi*_*uer 9

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

我个人使用system.eventStream来处理我的情况.

从演员那里,你可以发送给每个人:

context.system.eventStream.publish(StatisticsMessage())
Run Code Online (Sandbox Code Playgroud)

或直接与系统.

演员必须订阅:

context.system.eventStream.subscribe
Run Code Online (Sandbox Code Playgroud)

我延伸自:

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()
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 1.可能在“ postStop”中,您需要“取消订阅”;2.取消订阅_before_调用`super.postStop()`可能是一个更好的主意。 (2认同)