问题
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