简体   繁体   中英

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

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.

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 .

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM