Scala / Play / Akka:延迟动作响应

时间:2014-02-23 12:03:13

标签: scala concurrency playframework playframework-2.0

我有一个简单的Play应用程序,其中控制器动作调用模型方法,该方法执行一些计算并返回结果。我需要的是动作响应在1-5秒之间随机延迟。我对Akka没什么经验,但我不知道如何完成我需要的东西。

控制器示例:

package controllers

import scala.util.Random    
import play.api._
import play.api.mvc._

import models.MyModel

object Application extends Controller {

    def calculate = Action { implicit request =>

        val result = MyModel.calculate()
        val delay = Random.nextInt(6)

        //This response must be delayed somehow
        Ok(result)

    }

}

示例模型:

package models

object MyModel {

    def calculate = {

        //calculation happens here

    }

}

更新 - 解决方案 senia的答案正在运行,但有弃用警告。此代码与Play 2.2.1一致:

import play.api.libs.concurrent.Promise
import play.api.libs.concurrent.Execution.Implicits.defaultContext

def calculate = Action.async {

    val result = MyModel.calculate()
    val delay = Random.nextInt(6)
    val delayed = Promise.timeout(result, delay.second)
    delayed.map(Ok(_))

}

1 个答案:

答案 0 :(得分:3)

请参阅播放框架文档中的Handling asynchronous results /处理超时。

def calculate = Action.async { implicit request =>

  import play.api.libs.concurrent.Execution.Implicits.defaultContext
  import scala.concurrent.duration._

  val result = MyModel.calculate()
  val delay = Random.nextInt(6)

  val delayed = play.api.libs.concurrent.Promise.timeout(result, delay.seconds)

  delayed.map{Ok(_)}

}