action和action.async之间的区别

时间:2014-05-14 06:24:00

标签: scala playframework-2.0

我写了2个动作来测试action和action.asyc之间的区别。但是,我发现在Thread.sleep完成后,这两个方法都返回值。 action.asyc应该根据描述立即返回值吗?

def intensiveComputation(): Int = {
    Thread.sleep(5000)
    return 1
}

def testPromise() = Action {
   Ok("sync" + intensiveComputation())
}

def testPromise = Action.async {
   val futureint = scala.concurrent.Future { intensiveComputation() }
   futureint.map(i => Ok("async" + i))
}

1 个答案:

答案 0 :(得分:17)

正如您所观察到的那样,作为最终用户(即在浏览器中),您的两个代码段之间没有明显区别。

不同之处在于,对于你的"sync"情况,在Play中处理你的请求的整个线程/ actor / what-it-is已被束缚,在等待Thread.sleep时歪着拇指完成。

相比之下,在"async"情况下,处理函数实际上已经运行,因此运行它的资源(线程/参与者/其他)被释放以执行其他操作。当Future最终完成时,它可以完成工作。

看到差异的最好方法是撒上几个日志条目:

def intensiveComputation(): Int = {
  Logger.info("Sleeping")
  Thread.sleep(5000)
  Logger.info("Woke up")
  return 1
}

def testPromiseSync() = Action {
  val result = Ok("sync" + intensiveComputation())
  Logger.info("returning to Play")
  result
}

def testPromiseAsync = Action.async {
  val futureint = scala.concurrent.Future { intensiveComputation() }
  val f = futureint.map(i => Ok("async" + i))
  Logger.info("returning to Play")
  f
}

当我们点击sync端点时,我们会看到:

2014-05-14 17:23:39,359 [info] application - Sleeping
2014-05-14 17:23:44,359 [info] application - Woke up
2014-05-14 17:23:44,359 [info] application - returning to Play

async

2014-05-14 17:24:23,376 [info] application - Sleeping
2014-05-14 17:24:23,376 [info] application - returning to Play
2014-05-14 17:24:28,376 [info] application - Woke up

因此,通过使用Action.async,您可以释放Play以“一次”处理更多请求,同时保持最终用户体验不变。

相关问题