[英]How to Await in Play Framework 2 controller action?
我尝试编写动作以生成图片的缩略图,并向用户显示是否尚未生成。 问题是:生成部分异步运行,并在生成部分完成之前显示部分代码运行。 我是Scala和Play Framework的新手,无法参加演出。 我已经这样尝试过了:
def thumbs(profiletype: String, id: Int, filename: String, extention: String) = Action {
val content = File.getBinaryContent(pathToDir + filename + "." + extention)
content match {
case Some(c) => Ok(c).as(File.getContentType(extention))
case _ => val picture = Picture.getById(id)
picture match {
case None => NotFound("Page not found")
case Some(p) => val rslt = Future (p.generateThumbs(pathToDir, profiletype))
val r=rslt.map(a=>a)
Await.ready(r, Duration(8, "second"))
Logger.debug(pathToDir + filename + "." + extention)
val content = File.getBinaryContent(pathToDir + filename + "." + extention)
renderBinary(content, File.getContentType(extention))}
}
}
像这样没有运气
def thumbs(profiletype: String, id: Int, filename: String, extention: String) = Action {
val content = File.getBinaryContent(pathToDir + filename + "." + extention)
content match {
case Some(c) => Ok(c).as(File.getContentType(extention))
case _ => val picture = Picture.getById(id)
picture match {
case None => NotFound("Page not found")
case Some(p) => val rslt = Future (p.generateThumbs(pathToDir, profiletype))
Await.ready(rslt, Duration(8, "second"))
Logger.debug(pathToDir + filename + "." + extention)
val content = File.getBinaryContent(pathToDir + filename + "." + extention)
renderBinary(content, File.getContentType(extention))}
}
}
在p.generateThumbs完成之前,此等待不起作用并且Logger会记录日志
您可以返回Future[Result]
,而不是异步生成缩略图并在等待生成缩略图之前等待时阻塞(使用Await.ready
或Await.result
)。
在您的情况下,这看起来像(未经测试):
( 我还将您的Option
模式匹配转换为map
和getOrElse
函数。 )
def thumbs(
profiletype: String, id: Int, filename: String, extention: String
) = Action.async { // return an (explicit) asynchronous result
val filepath = pathToDir + filename + "." + extention
File.getBinaryContent(filepath)
.map ( content =>
// we found the thumbnail, return its content as a Future[Result]
Future.successful(Ok(content).as(File.getContentType(extention)))
)
.getOrElse {
// we have not found the thumbnail, check if the Picture exists
Picture.getById(id)
.map { picture =>
// we found the Picture, lets generate the thumbnails
Future(picture.generateThumbs(pathToDir, profiletype))
.map { futureResult =>
// the thumbnails are created
// return the content of the thumbnail
// and since we are in a Future.map this will be a Future[Result]
Logger.debug(filepath)
val content = File.getBinaryContent(filepath)
renderBinary(content, File.getContentType(extention))
}
}
// we could not find the Picture return a NotFound as Future[Result]
.getOrElse(Future.successful(NotFound("Page not found")))
}
}
这样,我们只有一个阻塞线程,而不是两个,而是创建一个缩略图,一个正在创建缩略图,另一个正在等待第一个线程完成创建缩略图。
在创建缩略图时,播放可以满足其他请求,在创建缩略图之后,播放将以缩略图进行响应。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.