Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 366
Rishav Basu Avatar asked Jan 08 '23 04:01

Rishav Basu


2 Answers

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.

like image 133
Chabreck Avatar answered Jan 10 '23 17:01

Chabreck


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.

like image 26
Carlos Vilchez Avatar answered Jan 10 '23 17:01

Carlos Vilchez