Search code examples
javaakkaevent-bus

Example of Akka EventBus for Java


Need some advice of how to use EventBus provided by Akka in Java (not Scala!). The documentation on website seems to be incomplete: http://doc.akka.io/docs/akka/2.0.1/java/event-bus.html

As far as I understood, actor should be created to react on specific messages, like:

final ActorSystem actorSystem = ActorSystem.create("ServerEvents");
final ActorRef actor = actorSystem.actorOf(new Props(SeverEventHandler.class));
actorSystem.eventStream().subscribe(actor,ServerMessage.class);

But now it's not clear how to send a message to the event bus.

Can somebody please share some good tutorials/examples/etc?


Solution

  • I think you're just one line short:

    final ActorSystem actorSystem = ActorSystem.create("ServerEvents");
    final ActorRef actor = actorSystem.actorOf(new Props(SeverEventHandler.class));
    actorSystem.eventStream().subscribe(actor,ServerMessage.class);
    
    actorSystem.eventStream().publish(new ServerMessage()); <<== add this
    

    While ServerEventHandler should be something like

    public class ServerEventHandler extends UntypedActor {
      @Override
      public void onReceive(final Object message) {
        System.out.println("Got event in thread: " + Thread.currentThread().getName());
        System.out.println("Event: " + message);
      }
    }