Search code examples
javaeventsakkaactor

Akka: dynamically add Actors to BroadcastRouter


What is the correct way to have a Broadcast actor dynamically add/remove routees over time?

Context of the problem: An actor listens to price changes of a particular item, then it broadcasts to all other actors (routees) the price change and they act according to internal rules (for example if the price is X buy or sell).

I am new to Akka, but after reading through the documentation I believe I have figured out the components needed but if you feel my design or components used are incorrect please comment/answer.

I want to change from a fixed list of routees

        ActorRef actor1 = system.actorOf(new Props(LimitOrderActor.class));
        ActorRef actor2 = system.actorOf(new Props(LimitOrderActor.class));
        ActorRef actor3 = system.actorOf(new Props(LimitOrderActor.class));
        Iterable<ActorRef> routees = Arrays.asList(new ActorRef[] { actor1, actor2, actor3 });
        ActorRef actorBroadcastRouter1 = system.actorOf(new Props(TickerWatcherActor.class).withRouter(BroadcastRouter.create(routees)), "router1");

To something like a dynamically sized BroadcastRouter where actors are created after the BroadcastRouter is up and running

        int lowerBound = 1;
        int upperBound = 10000;
        DefaultResizer resizer = new DefaultResizer(lowerBound, upperBound);
        BroadcastRouter broadcastRouter2 = new BroadcastRouter(resizer);
        ActorRef actorBroadcastRouter2 = system.actorOf(new Props(TickerWatcherActor.class).withRouter(broadcastRouter2), "router2");

        ActorRef actor4 = system.actorOf(new Props(LimitOrderActor.class).withRouter((RouterConfig) broadcastRouter2));
        ActorRef actor5 = system.actorOf(new Props(LimitOrderActor.class).withRouter((RouterConfig) broadcastRouter2));
        ActorRef actor6 = system.actorOf(new Props(LimitOrderActor.class).withRouter((RouterConfig) broadcastRouter2));

Right now the Actor "actorBroadcastRouter2" is receiving the message not the intended LimitOrderActor actors 4, 5 and 6. What am I doing wrong?

Edit: I believe now what I am looking for is the Event Bus not the BroadcastRouter

   final ActorRef actor = system.actorOf(new Props(LimitOrderActor.class));
   system.eventStream().subscribe(actor, String.class);

Solution

  • Use the Event Bus not the BroadcastRouter:

    final ActorRef actor = system.actorOf(new Props(LimitOrderActor.class));
    system.eventStream().subscribe(actor, String.class);