0

How can I broadcast a message to all actors that are watching a particular actor?

For context, suppose I have a AuctionActor (which is potentially a remote actor) that is being watched by a large number of AuctionParticipantActor types. I would like the AuctionActor to broadcast various messages to AuctionParicipantActor types.

One possibility would be for the AuctionActor to keep a collection of all participant ActorRef instances and then loop over this collection when ever a message needs to be sent to all participants. This seems inefficient and I am hoping for a better solution...

4

1 回答 1

1

如果您不想像 Diego Martinoia提到的那样使用 PubSub,我建议使用Routerswith BroadcastingLogic。这朝着您提到的 ActorRefs 集合的方向发展,但使用 Akka 功能来实现它比仅在AuctionActor.

来自 Akka文档

路由器被设计成非常有效地接收消息并将它们快速传递给路由。

一个普通的actor可以用来路由消息,但是一个actor的单线程处理可能会成为一个瓶颈。通过对允许并发路由的常用消息处理管道进行优化,路由器可以实现更高的吞吐量。

在您的情况下,它可能如下所示:

class AuctionActor extends Actor {
  var router = Router(BroadcastRoutingLogic(), Vector[ActorRefRoutee]())

  def receive = {
    case AddParticipant(ref) =>
      router = router.addRoutee(ref)
    case RemoveParticipant(ref) =>
      router = router.removeRoutee(ref)
    case update: ImportantUpdate =>
      router.route(update, self)
  }
}
于 2017-06-20T11:38:48.013 回答