向观看特定演员的演员广播消息?

Broadcast message to actors watching a particular actor?

如何向正在观看特定演员的所有演员广播消息?

对于上下文,假设我有一个 AuctionActor(它可能是一个远程参与者)正在被大量 AuctionParticipantActor 类型观看。我希望 AuctionActorAuctionParicipantActor 类型广播各种消息。

一种可能性是 AuctionActor 保留所有参与者 ActorRef 实例的集合,然后在需要向所有参与者发送消息时循环遍历该集合。这似乎效率低下,我希望有更好的解决方案...

如果您不想使用 Diego Martinoia 提到的 PubSub,我建议您使用 RoutersBroadcastingLogic。这与您提到的 ActorRefs 集合的方向一致,但使用 Akka 功能来实现它比仅迭代 AuctionActor.

中的集合更有效

来自阿卡Docs

Routers are designed to be extremely efficient at receiving messages and passing them quickly on to routees.

A normal actor can be used for routing messages, but an actor’s single-threaded processing can become a bottleneck. Routers can achieve much higher throughput with an optimization to the usual message-processing pipeline that allows concurrent routing.

在你的情况下它可能是这样的:

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)
  }
}