in akka suppose there is a linear chain of actors such that each actor receives a message from upstream, sends its own message downstream and waits for a reply, and then sends a message back upstream. how can the actor remember the handle of the开发者_Go百科 upstream actor when it has to reply to that actor later?
for example:
A sends message to B (b ! "msg1")
B sends message to C (c ! "msg2")
C replies to B (self.reply ! "msg3")
B replies to A <--- ???
basically, how can B remember a handle for A? doing self.reply at this point would refer to C, since C sent the current message to B.
Must actor B change the reply message between C and A ?
If not, actor B should use
B forward "msg"
instead ofB ! "msg"
. That will preserve the sender information. When C use reply, the answer is automatically sent to A without passing by B:A sends message to B (b ! "msg")
B forward the message to C (c forward "msg")
C replies to A (self.reply ! "msg3")
If yes, get the sender
ActorRef
and pass it along the message sender reference.
For example, using a simple tuple:
A sends message to B (b ! "msg1")
B sends message to C, with the sender reference (c ! ("msg2",self.sender) )
C replies to B adding the reference it received (self.reply ! ("msg3",ref) )
B replies to A ( ref ! "msg4" )
Here I used a Tuple, but if you have a longer chain, pass a List[ActorRef]
. When going forward, you prepend senders refs. And when going back, you reply to the list head and pass the list tail along the reply.
Edit: Taking Victor comment into account.
精彩评论