Reacting to Akka Remote Disconnects

This applies to akka 2.3

Using a reference to your actor system, define an Actor that will receive messages containing updates to the state of any remote actor.

Here is the Actor that we'll be using for this:

public class ClusterStateEventManager extends UntypedActor {

    private final ActorRef anotherActorToNotify;

    public ClusterStateEventManager(ActorRef anotherActorToNotify) {
        this.anotherActorToNotify = anotherActorToNotify;
    }

    @Override
    public void onReceive(Object message) throws Exception {

        if (message instanceof AssociatedEvent) {
            AssociatedEvent associatedEventMessage = (AssociatedEvent)message;
            String message = String.format("Node: %s Has Connected", associatedEventMessage.getRemoteAddress().toString());
            
            anotherActorToNotify.tell(message);
        }

        if (message instanceof DisassociatedEvent) {
            DisassociatedEvent disassociatedEvent = (DisassociatedEvent)message;

            Address address = disassociatedEvent.remoteAddress();

            String host = address.host().get();
            Integer port = (Integer)address.port().get();

            String message = String.format("Node %s:%d has Disconnected", host,port);
            
            anotherActorToNotify.tell(message,getSelf());
        }

    }

}

So assuming you have an instantiated ActorSystem named system first register your Actor

ActorRef actorRef = system.actorOf(Props.create(ClusterStateEventManager.class,anotherActorToNotify));

Then subscribe to your system's event stream

system.eventStream().subscribe(actorRef, RemotingLifecycleEvent.class);

Your Actor will you receive and process updates to remote node connections and disconnections

*****
Written by Ben Ashby on 18 December 2015