action和action.async之间的区别

vaj*_*oja 9 scala playframework-2.0

我写了两个动作来测试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))
}
Run Code Online (Sandbox Code Playgroud)

mil*_*use 16

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

区别在于,对于你的"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
}
Run Code Online (Sandbox Code Playgroud)

当我们点击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
Run Code Online (Sandbox Code Playgroud)

而且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
Run Code Online (Sandbox Code Playgroud)

因此,通过使用Action.async您释放Play来"立即"处理更多请求,同时保持最终用户体验不变.

  • “ ...……在Play中处理您的请求的整个线程/演员/无论它是什么都被绑住了**,它在等待Thread.sleep完成时摇动了大拇指。”这句话似乎有点使我困惑。由于默认情况下“播放中的操作”是异步的,因此线程“处理” **不会阻止该请求。 (2认同)