Let's say I have a Region Actor, and each region has a certain number of people inside it. How do you broadcast a message to everyone, knowing that the list of people can change over time, broadcast routers seems to be the choice, but then the problem is that they have a maximum number of routees, and that I cannot dynamically append people to a router.
My question is: I know there is an EventBus, I could subscribe my people to the event Bus, but I dont want them to recieve every message posted, I want them to recieve the messages of the region.
right now in akka, we have to create a router with a certain number of routees, example :
Router router = new router(person1, person2)
this is bad because At the beggining there is no one in the region, i don't know the people who will join my region.
is there a way to make a kind of dynamic router : example :
Region region = new region()
region.router = new Router()
Person person1 = new Person()
region.router.subscribe(person1);
region.router.tell("hello",null);
Your solution is already very close: you need a router, but not one of the special-made pre-fabricated ones. Instead just write an actor which forwards messages to subscribers:
class MyRouter extends UntypedActor {
final Set<ActorRef> subscribers = new HashSet<ActorRef>();
@Override public void onReceive(Object msg) {
if (msg instanceof Subscribe) {
subscribers.add(getSender());
} else if (msg instanceof Unsubscribe) {
subscribers.remove(getSender());
} else {
for (ActorRef target: subscribers) {
target.tell(msg, getSender());
}
}
}
}
来源:https://stackoverflow.com/questions/15721741/akka-java-non-blocking-broadcast-to-all-children