Reputation: 581
If I use the code below (from http://doc.akka.io/docs/akka/2.0/scala/routing.html), how do the routees
refer to/communicate with router2
(without using sender()
), as the context.parent
does not work?
val actor1 = system.actorOf(Props[ExampleActor1])
val actor2 = system.actorOf(Props[ExampleActor1])
val actor3 = system.actorOf(Props[ExampleActor1])
val routees = Vector[ActorRef](actor1, actor2, actor3)
val router2 = system.actorOf(Props[ExampleActor1].withRouter(
RoundRobinRouter(routees = routees)))
Upvotes: 0
Views: 96
Reputation: 7257
As you've currently written it, they can't. You'll have to pass the router's ActorRef
to the routees explicitly.
The other option is the let the router create its routees as then the routees' context.parent
will refer to the router.
Upvotes: 1
Reputation: 35463
If you really want a routee to be able to communicate with other routees over the router then you could send the router (introduce it) into the routees as a message after everything is created. From there, you can Broadcast a message over the router to get it to all routees, but keep in mind that the broadcasting routee will also receive the same message. Something like this:
object MyActor{
case class SetParent(ref:ActorRef)
case class OtherMessage(s:String)
}
class MyActor extends Actor{
import MyActor._
def receive = myReceive()
def myReceive(parentOpt:Option[ActorRef] = None):Receive = {
case SetParent(parent) => context.become(myReceive(Some(parent)))
case OtherMessage(msg) => println(s"Got other message: $msg")
case someOtherMsg =>
parentOpt foreach (parent => Broadcast(OtherMessage("hello world")))
}
}
Then, your actor creation logic looks like this:
val actor1 = system.actorOf(Props[ExampleActor1])
val actor2 = system.actorOf(Props[ExampleActor1])
val actor3 = system.actorOf(Props[ExampleActor1])
val routees = Vector[ActorRef](actor1, actor2, actor3)
val router2 = system.actorOf(Props[ExampleActor1].withRouter(
RoundRobinRouter(routees = routees)))
routees foreach (r => r ! SetParent(router))
Upvotes: 0