Search code examples
akkaakka-cluster

What's the best way to get an ActorRef from a Cluster given a relative path?


I have an Akka application having several nodes in a cluster. Each node runs an assortment of different Actors, i.e. not all nodes are the same--there is some duplication for redundancy.

I've tried code like this to get a ref to communicate with an Actor on another node:

val myservice = context.actorSelection("akka.tcp://[email protected]:2552/user/myService")

This works, because there is an Actor named myService running on the node at that address. That feels like simple Akka Remoting though, not clustering, because the address is point-to-point.

I want to ask the cluster "Hey! Anybody out there have an ActorRef at path "/user/myService"?", and get back one or more refs (depending on how many redundant copies are out there). Then I could use that selector to communicate.


Solution

  • Consider using Cluster Sharding, which would remove the need to know exactly where in the cluster your actors are located:

    Cluster sharding is useful when you need to distribute actors across several nodes in the cluster and want to be able to interact with them using their logical identifier, but without having to care about their physical location in the cluster, which might also change over time.

    With Cluster Sharding, you don't need to know an actor's path. Instead, you interact with ShardRegion actors, which delegate messages to the appropriate node. For example:

    val stoutRegion: ActorRef = ClusterSharding(system).shardRegion("Stout")
    stoutRegion ! GetPint("guinness")