我正在开发一个使用actor来处理请求的播放应用程序。应用程序外线将是这样的..
MyController extends Controller {
system.actorOf(Props(new MyRequestProcessor))
val actorRef = MyRequestProcessor
def handle(parse.json) { request =>
actorRef ! request.body
Ok
}
}
基本上我想将MyRequestProcessor actor放在Supervisor actor下。由于控制器是由play框架创建的,我不知道在Supervisor中创建RequestProcessor并获取ActorRef的首选方法。
希望代码是这样的......
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
}
}
答案 0 :(得分:2)
请问它。
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)
}