Asynchronous 使用动作合成时播放2异步
在Play2中,我理解了动作组合和使用异步{…}进行异步响应的概念,但我还没有看到这些方法一起使用的示例 为了清楚起见,假设您正在使用动作合成来确保对用户进行身份验证:Asynchronous 使用动作合成时播放2异步,asynchronous,playframework-2.0,Asynchronous,Playframework 2.0,在Play2中,我理解了动作组合和使用异步{…}进行异步响应的概念,但我还没有看到这些方法一起使用的示例 为了清楚起见,假设您正在使用动作合成来确保对用户进行身份验证: def index = Authenticated { user => Action { request => Async { Ok("Hello " + user.name) } } } 在Authenticated的实现中,如果我们假设正在查找
def index = Authenticated { user =>
Action { request =>
Async {
Ok("Hello " + user.name)
}
}
}
在Authenticated
的实现中,如果我们假设正在查找此数据库以检索用户,那么在我看来,这部分将是一个阻塞调用,只将操作
主体中的响应保留为非阻塞
有人能解释一下我如何做非阻塞异步I/O,它也包括身份验证部分吗?我的解决方案是由内而外组合动作,如下所示:
def index = Action { request =>
Async {
Authenticated { user =>
Ok("Hello " + user.name)
}
}
}
然后,我的已验证的
签名将类似于:
def Authenticated(body: => Result): Result = {
// authenticate, and then
body
}
这里的缺点是,正文解析将在身份验证之前进行,这对您来说可能是个问题,也可能不是问题。我可以给出一个完整的示例: 其实质是:
def WithAuthentication(f: WithAuthentication => Result) = Action {
implicit request => AsyncResult {
// async auth logic goes here
}
}
仅在控制器中:
def indexAction = WithAuthentication {
implicit request =>
Ok(views.html.index())
}
甚至:
def someAction = WithAuthentication {
implicit request => Async {
// more async logic here
}
}
这是一个模板友好的解决方案,请随意使用。也许有时候我会从中创建一个插件。刚刚为我的应用程序编写了代码,到目前为止,它似乎工作正常