I have two actors A and B. A Controller sends a request to actor A. Now actor A return a response of type Try[AbcResponse]
. AbcResponse
being a case class here. Actor A based on some logic might directly return this response or it might conditionally call another actor B using ask. After manipulating the response from B it would then send the response of type Try[AbcResponse]
to the controller.
So what should i do in my actor A to handle this situation. I do not want to put a await in my actor A because that would waste the thread pool and cause slowdowns in the system. How can i efficiently handle this?
You could pass the sender reference in a message to actor B and pipe
the response from actor B to self
. Obviously actor B in its response would have to pass this reference back to actor A.
import akka.pattern.{ask, pipe}
case class MsgToActorB(..., target: ActorRef)
case class ResponseFromActorB(..., target: ActorRef)
class ActorA extends Actor {
def receive = {
case r: Request =>
val s = sender
implicit val timeout = Timeout(5 seconds)
// do something with the request
if (someCondition)
s ! Try(AbcResponse(...))
else
(actorB ? MsgToActorB(..., s)).mapTo[ResponseFromActorB].pipeTo(self)
case ResponseFromActorB(..., target) =>
// do something with the response from B and send a response to the original sender
target ! Try(AbcResponse(...))
}
}
While the above approach is safe, it'd be simpler to not use ask
as shown below. If you must use ask
and if actor B is blocking when it processes a message from actor A, then consider configuring a separate dispatcher as described here .
def receive = {
case r: Request =>
val s = sender
// do something with the request
if (someCondition)
s ! Try(AbcResponse(...))
else
actorB ! MsgToActorB(..., s)
case ResponseFromActorB(..., target) =>
// do something with the response from B and send a response to the original sender
target ! Try(AbcResponse(...))
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.