Action 组合不足以完成这项工作,但 Action 组合 + Future 或 Action 组合 + Actors 是实现这一目标的好方法。
动作组合+未来
生成您的响应,在异步上下文中启动您的日志记录/处理,并同时发送结果。
def LoggedAction(f: Request[AnyContent] => Result) = Action { request =>
val result = f(request)
concurrent.future(myLogAction(request, result))
result
}
动作组合+演员
这是实现这一目标的一种更清洁的方式。与前一种情况一样,生成您的响应,将日志记录/处理事件发送给您的参与者,并同时发送结果。
import play.api._
import play.api.mvc._
import play.libs._
import akka.actor._
object Application extends Controller with Finally {
def index = LoggedAction { r =>
Ok(views.html.index("Your new application is ready."))
}
}
trait Finally {
self: Controller =>
lazy val logActor = Akka.system.actorOf(Props(new LogActor), name = "logActor")
def LoggedAction(f: Request[AnyContent] => Result) = Action { request =>
val result = f(request) // Generate response
logActor ! LogRequest(request) // Send log event to LogActor
println("-> now send page to client")
result
}
case class LogRequest(request: Request[AnyContent])
class LogActor extends Actor {
def receive = {
case LogRequest(req) => {
println(req.host)
// ....
}
}
}
}
// Console
-> now send page to client
127.0.0.1:9000