Actor discovery

Dependency

To use Akka Actor Typed, you must add the following dependency in your project:

sbt
libraryDependencies += "com.typesafe.akka" %% "akka-actor-typed" % "2.5.14"
Maven
<dependency>
  <groupId>com.typesafe.akka</groupId>
  <artifactId>akka-actor-typed_2.12</artifactId>
  <version>2.5.14</version>
</dependency>
Gradle
dependencies {
  compile group: 'com.typesafe.akka', name: 'akka-actor-typed_2.12', version: '2.5.14'
}

Introduction

With untyped actors you would use ActorSelection to “lookup” actors. Given an actor path with address information you can get hold of an ActorRef to any actor. ActorSelection does not exist in Akka Typed, so how do you get the actor references? You can send refs in messages but you need something to bootstrap the interaction.

Receptionist

For this purpose there is an actor called the Receptionist. You register the specific actors that should be discoverable from other nodes in the local Receptionist instance. The API of the receptionist is also based on actor messages. This registry of actor references is then automatically distributed to all other nodes in the cluster. You can lookup such actors with the key that was used when they were registered. The reply to such a Find request is a Listing, which contains a Set of actor references that are registered for the key. Note that several actors can be registered to the same key.

The registry is dynamic. New actors can be registered during the lifecycle of the system. Entries are removed when registered actors are stopped or a node is removed from the cluster. To facilitate this dynamic aspect you can also subscribe to changes with the Receptionist.Subscribe message. It will send Listing messages to the subscriber when entries for a key are changed.

The first scenario is an actor running that needs to be discovered by another actor but you are unable to put a reference to it in an incoming message.

First we create a PingService actor and register it with the Receptionist against a ServiceKey that will later be used to lookup the reference:

Scala
val PingServiceKey = ServiceKey[Ping]("pingService")

final case class Ping(replyTo: ActorRef[Pong.type])
final case object Pong

val pingService: Behavior[Ping] =
  Behaviors.setup { ctx ⇒
    ctx.system.receptionist ! Receptionist.Register(PingServiceKey, ctx.self)
    Behaviors.receive[Ping] { (_, msg) ⇒
      msg match {
        case Ping(replyTo) ⇒
          replyTo ! Pong
          Behaviors.stopped
      }
    }
  }
Java
static final ServiceKey<Ping> PingServiceKey =
  ServiceKey.create(Ping.class, "pingService");

public static class Pong {}
public static class Ping {
  private final ActorRef<Pong> replyTo;
  Ping(ActorRef<Pong> replyTo) {
    this.replyTo = replyTo;
  }
}

static Behavior<Ping> pingService() {
  return Behaviors.setup((ctx) -> {
    ctx.getSystem().receptionist()
      .tell(Receptionist.register(PingServiceKey, ctx.getSelf()));
    return Behaviors.receive(Ping.class)
      .onMessage(Ping.class, (c, msg) -> {
        msg.replyTo.tell(new Pong());
        return Behaviors.same();
      }).build();
  });
}

Then we have another actor that requires a PingService to be constructed:

Scala
def pinger(pingService: ActorRef[Ping]) = Behaviors.setup[Pong.type] { ctx ⇒
  pingService ! Ping(ctx.self)
  Behaviors.receive { (_, msg) ⇒
    println("I was ponged!!" + msg)
    Behaviors.same
  }
}
Java
static Behavior<Pong> pinger(ActorRef<Ping> pingService) {
  return Behaviors.setup((ctx) -> {
    pingService.tell(new Ping(ctx.getSelf()));
    return Behaviors.receive(Pong.class)
      .onMessage(Pong.class, (c, msg) -> {
        System.out.println("I was ponged! " + msg);
        return Behaviors.same();
      }).build();
  });
}

Finally in the guardian actor we spawn the service as well as subscribing to any actors registering against the ServiceKey. Subscribing means that the guardian actor will be informed of any new registrations via a Listing message:

Scala
val guardian: Behavior[Nothing] = Behaviors.setup[Listing] { ctx ⇒
  ctx.system.receptionist ! Receptionist.Subscribe(PingServiceKey, ctx.self)
  val ps = ctx.spawnAnonymous(pingService)
  ctx.watch(ps)
  Behaviors.receiveMessagePartial[Listing] {
    case PingServiceKey.Listing(listings) if listings.nonEmpty ⇒
      listings.foreach(ps ⇒ ctx.spawnAnonymous(pinger(ps)))
      Behaviors.same
  } receiveSignal {
    case (_, Terminated(`ps`)) ⇒
      println("Ping service has shut down")
      Behaviors.stopped
  }
}.narrow
Java
static Behavior<Void> guardian() {
  return Behaviors.setup((ctx) -> {
    ctx.getSystem().receptionist()
      .tell(Receptionist.subscribe(PingServiceKey, ctx.getSelf().narrow()));
    ActorRef<Ping> ps = ctx.spawnAnonymous(pingService());
    ctx.watch(ps);
    return Behaviors.receive(Object.class)
      .onMessage(Receptionist.Listing.class, listing -> listing.isForKey(PingServiceKey), (c, msg) -> {
      msg.getServiceInstances(PingServiceKey).forEach(ar -> ctx.spawnAnonymous(pinger(ar)));
      return Behaviors.same();
    }).build();
  }).narrow();
}

Each time a new (which is just a single time in this example) PingService is registered the guardian actor spawns a pinger to ping it.

Cluster Receptionist

The Receptionist also works in a cluster, an actor registered to the receptionist will appear in the receptionist of the other nodes of the cluster.

The state for the receptionist is propagated via distributed data which means that each node will eventually reach the same set of actors per ServiceKey.

One important difference from a local only receptions is the serialisation concerns, all messages sent to and back from an actor on another node must be serializable, see clustering.

Found an error in this documentation? The source code for this page can be found here. Please feel free to edit and contribute a pull request.