使用Play.async会产生什么效果,因为Play使用的是非阻塞性Netty [英] What effect does using Action.async have, since Play uses Netty which is non-blocking

查看:118
本文介绍了使用Play.async会产生什么效果,因为Play使用的是非阻塞性Netty的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于Netty是非阻塞服务器,因此将操作更改为使用.async有什么作用?

def index = Action { ... }

def index = Action.async { ... }

我了解使用.async会得到一个Future[SimpleResult].但是由于Netty是无障碍的,所以Play会在幕后做类似的事情吗?

这将对吞吐量/可伸缩性产生什么影响?这是一个很难回答的问题,它取决于其他因素吗?

我要问的原因是,我有自己的自定义Action,我想为每个页面请求重置Cookie超时,所以我这样做是通过async调用:

object MyAction extends ActionBuilder[abc123] {
  def invokeBlock[A](request: Request[A], block: (abc123[A]) => Future[SimpleResult]) = {
    ...
    val result: Future[SimpleResult] = block(new abc123(..., result))
    result.map(_.withCookies(...))
  }
}

以上代码片段的好处是我正在使用Future[SimpleResult],这类似于调用Action.async,但这在我的Action本身之内吗?

我想了解这会对我的应用程序设计产生什么影响.似乎只是为了能够按请求设置我的Cookie,我已从阻止更改为非阻止.但是由于Netty是非阻塞性的,我感到困惑,也许我还没有真正改变任何现实,因为它已经异步了?

还是我只是简单地创建了一个嵌入在另一个异步调用中的异步调用?

希望有人可以详细说明这一点,以及这将对性能/吞吐量产生何种影响或产生什么影响.

解决方案

def index = Action { ... }是无障碍的,您是对的.

Action.async的目的仅仅是为了使您在操作中使用Futures更加容易.

例如:

def index = Action.async {
  val allOptionsFuture: Future[List[UserOption]] = optionService.findAll()
  allOptionFuture map {
    options =>
      Ok(views.html.main(options))
  }
}

在这里,我的服务返回了Future,为避免处理提取结果,我将其映射到Future[SimpleResult],而Action.async负责其余的工作.

如果我的服务直接返回List[UserOption],我可以只使用Action.apply,但是在幕后它仍然是非阻塞的.

如果查看Action源代码,甚至可以看到apply最终会调用async: 解决方案

def index = Action { ... } is non-blocking you are right.

The purpose of Action.async is simply to make it easier to work with Futures in your actions.

For example:

def index = Action.async {
  val allOptionsFuture: Future[List[UserOption]] = optionService.findAll()
  allOptionFuture map {
    options =>
      Ok(views.html.main(options))
  }
}

Here my service returns a Future, and to avoid dealing with extracting the result I just map it to a Future[SimpleResult] and Action.async takes care of the rest.

If my service was returning List[UserOption] directly I could just use Action.apply, but under the hood it would still be non-blocking.

If you look at Action source code, you can even see that apply eventually calls async: https://github.com/playframework/playframework/blob/2.3.x/framework/src/play/src/main/scala/play/api/mvc/Action.scala#L432

这篇关于使用Play.async会产生什么效果,因为Play使用的是非阻塞性Netty的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆