【问题标题】:Consuming a service using WS in Play在 Play 中使用 WS 消费服务
【发布时间】:2015-03-15 02:26:09
【问题描述】:

我希望有人可以简要介绍一下使用服务的各种方式(这个只是返回一个字符串,通常是 JSON,但我只是想了解这里的概念)。

我的服务:

def ping = Action {
  Ok("pong")
}

现在在我的 Play (2.3.x) 应用程序中,我想调用我的客户端并显示响应。

使用 Futures 时,我想显示值。 我有点困惑,我可以调用这个方法的所有方法,即我看到有一些方法使用成功/失败,

val futureResponse: Future[String] = WS.url(url + "/ping").get().map { response =>
          response.body
 }
var resp = ""
futureResponse.onComplete {
  case Success(str) => {
    Logger.trace(s"future success $str")
    resp = str
  }
  case Failure(ex) => {
    Logger.trace(s"future failed")
    resp = ex.toString
  }
}

Ok(resp)

我可以在 STDOUT 中看到成功/失败的跟踪,但我的控制器操作只是将“”返回到我的浏览器。

我知道这是因为它返回一个 FUTURE 并且我的操作在未来返回之前完成。

如何强制它等待? 我有哪些错误处理选项?

【问题讨论】:

    标签: scala future playframework-2.3


    【解决方案1】:

    如果您真的想阻止直到功能完成,请查看 Future.ready()Future.result() 方法。但你不应该。

    Future 的要点是,你可以告诉它一旦结果到达后如何使用它,然后继续,不需要阻塞。

    Future 可以是Action 的结果,在这种情况下框架会处理它:

    def index = Action.async {
      WS.url(url + "/ping").get()
        .map(response => Ok("Got result: " + response.body))
    }
    

    documentation,主题描述得很好。

    至于错误处理,您可以使用Future.recover() 方法。您应该告诉它在发生错误时要返回什么,它会为您提供新的Future,您应该从您的操作中返回。

    def index = Action.async {
      WS.url(url + "/ping").get()
        .map(response => Ok("Got result: " + response.body))
        .recover{ case e: Exception => InternalServerError(e.getMessage) }
    }
    

    因此,您使用服务的基本方式是获取结果Future,通过使用单子方法(返回新转换后的Future 的方法,如maprecover 等)以您想要的方式转换它..) 并将其作为Action 的结果返回。

    您可能需要查看Play 2.2 -Scala - How to chain Futures in Controller ActionDealing with failed futures 问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-15
      • 1970-01-01
      • 2018-04-06
      • 1970-01-01
      • 1970-01-01
      • 2020-12-22
      • 2010-10-16
      • 2016-03-17
      相关资源
      最近更新 更多