Reputation: 137
I was looking at the Akka documentation for some examples on routers.
From the documentation:
By default, when a routee sends a message, it will implicitly set itself as the sender.
sender ! x // replies will go to this actor
However, it is often useful for routees to set the router as a sender. For example, you might want to set the router as the sender if you want to hide the details of the routees behind the router. The following code snippet shows how to set the parent router as sender.
sender.tell("reply", context.parent) // replies will go back to parent
sender.!("reply")(context.parent) // alternative syntax (beware of the parens!)
Note that different code would be needed if the routees were not children of the router, i.e. if they were provided when the router was created.
Link: http://doc.akka.io/docs/akka/2.2.3/scala/routing.html
My question is I have written a code where the routees were provided and they're not the children. As expected, the above method doesn't work. What is the different code that is needed here?
Upvotes: 0
Views: 234
Reputation: 15074
What you will probably want to do here is have the router send its "self" ref to each of the routees, which can then set the sender via:
sender.tell("reply", routerRef) // or
sender.!("reply")(routerRef)
You will need to determine an appropriate message (maybe just an ActorRef
, or maybe a case class that suggests the usage, eg: case class RouterRef(ref: ActorRef)
), and have the routee receive method able to accept such a message and store it. An example might be:
class MyRoutee(...) extends Actor with ActorLogging with ... {
import context._
def receive = init
def init: Receive = LoggingReceive { // Initially waits for router ref (and/or any other initialisation info it needs to be fed with)
case RouterRef(ref) => become(active(ref)) // Received the router ref - change behaviour
}
def active(routerRef: ActorRef): Receive = LoggingReceive {
... // Normal running mode - routerRef is available
}
}
Upvotes: 1