How to broadcast message to all actors in an AKKA cluster in java?

帅比萌擦擦* 提交于 2019-12-10 19:36:30

问题


I have an AKKA cluster system with name say ClusterSystem. Each node of this cluster have an actor ActorA. I want a way to broadcast a message sent to an actor to all the ActoraA-s running in the cluster.

It would be of great help if any one can post an example in Java.


回答1:


Check out the Distributed Publish Subscribe extension. It lets you subscribe one or more actors to a topic, and publish messages to this topic from any actor in the cluster.

Subscribing:

class Subscriber extends Actor with ActorLogging {
  import DistributedPubSubMediator.{ Subscribe, SubscribeAck }
  val mediator = DistributedPubSub(context.system).mediator
  // subscribe to the topic named "content"
  mediator ! Subscribe("content", self)

  def receive = {
    case s: String ⇒
      log.info("Got {}", s)
    case SubscribeAck(Subscribe("content", None, `self`)) ⇒
      log.info("subscribing");
  }
}

Publishing:

class Publisher extends Actor {
  import DistributedPubSubMediator.Publish
  // activate the extension
  val mediator = DistributedPubSub(context.system).mediator

  def receive = {
    case in: String ⇒
      val out = in.toUpperCase
      mediator ! Publish("content", out)
  }
}

Code examples and additional explanation here.




回答2:


There is an special type of message for this task. You can send a Broadcast message to a router and it will be received by all the routees.

router.tell(new Broadcast("Watch out for Davy Jones' locker"), getTestActor());

You can also create a BroadcastPool and BroadcastGroup in case that you need to broadcast every single message.

You can find more information about both options in this link.



来源:https://stackoverflow.com/questions/30772983/how-to-broadcast-message-to-all-actors-in-an-akka-cluster-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!