What effect does using Action.async have, since Play uses Netty which is non-blocking

后端 未结 2 1606
梦毁少年i
梦毁少年i 2021-02-04 04:57

Since Netty is a non-blocking server, what effect does changing an action to using .async?

def index = Action { ... }

versus

2条回答
  •  名媛妹妹
    2021-02-04 05:03

    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

提交回复
热议问题