问题
What is the method for an actor to send a message to its parent?
I'm using Akka 2.2
回答1:
You are looking for
getContext().parent()
which gives you the ActorRef of the parent, so you can do
getContext().parent().tell(...)
回答2:
With Akka 2.4, you have to do context.parent
inside an actor to have its parent actor reference. After that, you can send it a message as before (context.parent ! "hello"
).
回答3:
It should be noted, e.g. for anybody who comes to this question through a search, that Akka 2.6 introduces a typed API for interacting with and defining actors and that the docs starting in version 2.6 guide towards using the typed API.
In an actor defined using the typed API, the ActorContext
no longer directly provides an ActorRef
to the parent actor, so the answers above won't work. See this question for a (Scala) solution in Akka Typed. The analogous Java API would be:
import akka.actor.typed.javadsl.Adapter
ActorRef parent = Adapter.toClassic(getContext()).parent()
Note that this is an untyped ActorRef
: you can send any message to the parent actor, but the parent actor is not under any obligation to accept the message you send.
来源:https://stackoverflow.com/questions/17853573/how-to-send-a-message-to-an-actors-parent-in-akka-classic