【问题标题】:Nesting Futures in Play Action在 Play Action 中嵌套 Future
【发布时间】:2016-02-25 16:00:01
【问题描述】:

我正在使用 Play 并且有一个动作,我想做两件事:-

  1. 首先检查我的缓存中的值
  2. 其次,调用具有值的 Web 服务

由于 WS API 返回Future,我使用的是Action.async
我的 Redis 缓存模块也返回一个Future

假设我正在为可能长时间运行的任务适当地使用另一个 ExecutionContext。

问。有人可以通过执行以下操作来确认我是否走在正确的轨道上。我知道我没有处理下面的特殊情况 - 只是为了简洁起见。

def token = Action.async { implicit request =>


    // 1. Get Future for read on cache

    val cacheFuture = scala.concurrent.Future {   
        cache.get[String](id)    
    }


    // 2. Map inside cache Future to call web service

    cacheFuture.map { result =>   

        WS.url(url).withQueryString("id" -> result).get().map { response =>
            // process response
            Ok(responseData)
        }

    }

}

我担心这可能不是最有效的做事方式,因为我假设不同的线程可能会处理完成每个 Futures 的任务。

非常感谢任何有关更好方法的建议。

【问题讨论】:

    标签: scala playframework playframework-2.0


    【解决方案1】:

    这并不是 Play 特有的。我建议您查看说明 Futures 工作原理的文档。

    val x: Future[FutureOp2ResType] = futureOp1(???).flatMap { res1 => futureOp2(res1, ???) }
    

    或者为了理解

    val x: Future[TypeOfRes] = for {
      res1 <- futureOp1(???)
      res2 <- futureOp2(res1, ???)
      // ...
    } yield res
    

    至于Futures 的执行方式(使用线程),这取决于您使用哪个ExecutionContext(例如,全局的、Play 的...)。

    WS.get 返回一个Future,它不应该在cacheFuture.map 内调用,否则它会返回一个Future[Future[...]]

    【讨论】:

    • 好的 cchantep 感谢 cmets。如果它有助于解决我的问题,我将在文档中进行更多挖掘并回来。
    猜你喜欢
    • 2021-07-22
    • 2013-12-15
    • 2019-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-02
    • 1970-01-01
    • 2021-09-22
    相关资源
    最近更新 更多