问题
If I create an actor using context().actorOf() in Akka, I get back a valid ActorRef. However, if I do the same but create an ActorRef using actorFor and the path I know that the actor will appear at, I do not reliably get a valid ActorRef back. How can I tell that an actor has been registered successfully?
In the description above, I could simply use the ActorRef returned from actorOf(). However, in my actual case I create an actor that itself registers a child actor and I need to resolve that, so the problem in general is "how can I wait / register to be informed of an actor having been registered at a known path?".
回答1:
First of all, there's no guarantee that the ActorRef you get back from actorOf is still alive, since the constructor of it could have failed.
Secondly, actorFor might find the actor but it died just after being found and just before you started working with it.
Thirdly, it's normally good practice to structure your application so that dependencies are propagated in a logical fashion, so that there is a natural rendez-vous point between your actors.
Hope any of the above helps,
happy hAkking!
√
回答2:
Since Akka 2.2.1 you can use ActorSelection.resolveOne to get an ActorRef from an actor selection:
implicit val timeout = Timeout(5, TimeUnit.SECONDS)
val selection = system.actorSelection("/user/myActor")
val actor = Await.result(selection.resolveOne(), timeout.duration)
From the docs http://doc.akka.io/api/akka/2.2.1/index.html#akka.actor.ActorSelection
Resolve the ActorRef matching this selection. The result is returned as a Future that is completed with the ActorRef if such an actor exists. It is completed with failure ActorNotFound if no such actor exists or the identification didn't complete within the supplied timeout.
Under the hood it talks to the actor to verify its existence and acquire its ActorRef.
来源:https://stackoverflow.com/questions/10549026/in-akka-how-do-i-know-when-an-actor-is-ready-to-use-after-having-been-registere