Vishal John
Vishal John

Reputation: 4382

Supervisor Actor in Play

I am developing a play application which uses actors to process the requests. Application out line would be something like this..

MyController extends Controller {

  system.actorOf(Props(new MyRequestProcessor))
  val actorRef = MyRequestProcessor

  def handle(parse.json) { request =>
    actorRef ! request.body
    Ok
  }

}

Basically i would like to put the MyRequestProcessor actor under a Supervisor actor. Since the controllers are created by the play framework, I don't know the preferred way to create RequestProcessor with in a Supervisor and get the ActorRef back.

Want the code to be something like this...

 Supervisor extends Actor {

   override val supevisorStrategy = OneForOneStrategy….

 }

 MyController extends Controller {

  val supervisorRef = system.actorOf(Props[Supervisor]...

  val processorRef = //NEED A WAY TO INSTANTIATE MyRequestProcessor WITHIN 
  //Supervisor and get that ActorRef back Using Supervisor's context.actorOf[]

 def handle(parse.json) { request
   processorRef ! request.body
 }

}

Upvotes: 3

Views: 1139

Answers (1)

agilesteel
agilesteel

Reputation: 16859

Just ask for it.

import akka.actor._
import akka.pattern.ask
import scala.concurrent.Await
import scala.concurrent.duration._
import akka.util.Timeout

object Supervisor {
   case object GetChild
}

class Supervisor(childProps: Props) extends Actor {
   import Supervisor._

   val child = context.actorOf(childProps, name = "child")

   def receive = {
      case GetChild => sender ! child
   }
}

class Child extends Actor {
   def receive = Actor.emptyBehavior
}

object MyController extends Controller {
   val system = ActorSystem("my-system")
   val supervisor = system.actorOf(Props(classOf[Supervisor], Props[Child]), name = "parent")
   implicit val timeout = Timeout(5 seconds)
   // Blocking is not ideal, but is not the point in this example anyway
   val child = Await.ready((supervisor ? GetChild).mapTo[ActorRef], timeout.duration)
}

Upvotes: 2

Related Questions