0
votes

I came across a scenario where I need to check if whether particular actor exists or not which can be done via ActorSystem.actorSelection method by specifying actor path.

However this method works correctly when such actor exists on your local node. If actor-system is formed by multiple nodes and actor exists on another node, this method tells that actor doesn't exist. If I give string that specifies remote actor-system then this method works. But this doesn't seem very good idea to specify remote actor-system string in actorSelection method as nodes in cluster can be joining and leaving.

def getOrCreate(customerId: String, deviceId: String): Future[ActorRef] = {
    context.system.actorSelection(s"/user/${customerId}{$deviceId}") ? Identify(deviceId) map {
    case ActorIdentity(`deviceId`, None) =>
      // create new actor
    case ActorIdentity(`deviceId`, Some(actor)) =>
      actor
  }
}

above code works fine when actor exists on local node, in order to check if actor exists on some another node in cluster, I had to do something like:

def getOrCreate(customerId: String, deviceId: String): Future[ActorRef] = {
    context.system.actorSelection(s"akka.tcp://Relay@node1:3503/user/${customerId}{$deviceId}") ? Identify(deviceId) map {
    case ActorIdentity(`deviceId`, None) =>
      // create new actor
    case ActorIdentity(`deviceId`, Some(actor)) =>
      actor
  }
}



Is there any better way of checking is actor exists in entire akka-cluster and not just local node?

1

1 Answers

2
votes

It looks like you want to create an actor instance only if no actor with the same identifier already exists in the cluster. For this, I think the best way to go is to use Akka cluster sharding and let Akka take care of creating and distributing the instances. This will also take care of routing any messages to the actor to the right node, redistributing the actors if the cluster size changes etc.