Tar*_*mar 1 asynchronous scala akka playframework playframework-2.0
我试图创建异步api.但响应显示顺序执行.完成的步骤:在两个chrome选项卡中打开url.然后快速地打击他们.url ex: - localhost:9000/getStar
.
但执行日志如下: -
[info] play - Listening for HTTP on /0:0:0:0:0:0:0:0:9000
(Server started, use Ctrl+D to stop and go back to the console...)
[success] Compiled in 107ms
[info] application - Application has started
[info] play - Application started (Dev)
[info] application - Async started ************************** :tarun
[info] application - Success Async call :1
[info] application - Success Async call :2
[info] application - Success Async call :3
[info] application - Success Async call :4
[info] application - Success Async call :5
[info] application - Success Async call :6
[info] application - Success Async call :7
[info] application - Success Async call :8
[info] application - Success Async call :9
[info] application - Async finished ************************** :tarun
[info] application - Async started ************************** :tarun1
[info] application - Success Async call :1
[info] application - Success Async call :2
[info] application - Success Async call :3
[info] application - Success Async call :4
[info] application - Success Async call :5
[info] application - Success Async call :6
[info] application - Success Async call :7
[info] application - Success Async call :8
[info] application - Success Async call :9
[info] application - Async finished ************************** :tarun1
Run Code Online (Sandbox Code Playgroud)
这个代码是:
package controllers
import play.Logger
import play.api.libs.json.Json
import play.api.mvc._
import scala.concurrent.Future
object StarController extends Controller {
import play.api.libs.concurrent.Execution.Implicits.defaultContext
def getStarAsync(name : String) = Action.async{
val futureResult = Future{
Logger.info("Async started ************************** :" + name)
val a = 0;
for( a <- 1 until 10) {
Thread.sleep(1000)
Logger.info("Success Async call :" + a.toString)
}
Logger.info("Async finished ************************** :" + name)
Map("success" -> Json.toJson(true), "msg" -> Json.toJson("Success Async by :" + name), "code" -> Json.toJson(200))
}
futureResult.map{ result =>
Ok(Json.toJson(result))
}
}
}
Run Code Online (Sandbox Code Playgroud)
任何人都可以帮助我理解,为什么即使使用异步调用执行顺序?
Action.async
不会神奇地使控制器方法异步.它唯一不同的是它期望一个Future[Result]
而不是一个Result
.而已.控制器在其他方面是异步的,因为它们本质上是可能的(即正常情况下Action
会被包裹起来Future
).这里的事情是Thread.sleep(1000)
阻塞它的线程,并且不是异步的.
另一件事是在开发模式(即activator run
)中,播放服务器使用单个线程来处理请求,因此它可以正确处理重载/编译,演进等.所以正在发生的事情是你只是用同步来阻止该线程调用.你应该看到使用不同的结果activator start
,但即便如此,Action.async
除非你要将阻塞委托给不同的线程池,否则在这里使用是没有意义的.
归档时间: |
|
查看次数: |
448 次 |
最近记录: |