【问题标题】:Why does mapTo fail in Akka HTTP client?为什么 mapTo 在 Akka HTTP 客户端中失败?
【发布时间】:2017-02-17 09:24:39
【问题描述】:

我有一个 Akka HTTP 服务,它返回一个字符串,如下所示:

val route1: Route = {
    path("hello") {
      get{
        complete{
          println("Inside r1")
          "You just accessed hello"
        }
      }
   }
}

我有一个 Akka HTTP 客户端,它试图访问这个路由。但是下面的代码失败了:

  val future1 = Http()
    .singleRequest(
      HttpRequest(method = HttpMethods.GET,
        uri = "http://localhost:8187/hello")).mapTo[String]

  future1.onSuccess({
    case y:String=>println(y)
  })

我根本没有输出。但是,如果我将 unmarshal 与 flatMap 一起使用,我会得到输出:

 val future1:Future[String] = Http()
    .singleRequest(
      HttpRequest(method = HttpMethods.GET,
                  uri = "http://localhost:8187/hello")).flatMap(resp => Unmarshal(resp).to[String])

为什么 mapTo 在这里失败,为什么我需要 flatMap 和 Unmarshal?

编辑:

我了解 Unmarhsal 的必要性,我正在尝试了解 map 和 flatMap 之间的区别

例如,下面的代码给了我预期的结果:

val future1:Future[String] = Http().singleRequest(
          HttpRequest(method = HttpMethods.GET,
                      uri = http://localhost:8187/hello")).flatMap(testFlatFunc)

  def testFlatFunc(x:HttpResponse):Future[String]={
    return Unmarshal(x).to[String]
  }

但是,如果我尝试用地图替换它,如下所示,我得到的输出为FulfilledFuture(You just accessed hello)

 val future1:Future[String] = Http()
    .singleRequest(
      HttpRequest(method = HttpMethods.GET,
                  uri = "http://localhost:8187/hello")).map(testFunc)

  def testFunc(x:HttpResponse): String={
    return Unmarshal(x).to[String].toString
  }

【问题讨论】:

    标签: scala akka spray akka-http spray-client


    【解决方案1】:

    请参阅下面mapTo 的文档

      /** Creates a new `Future[S]` which is completed with this `Future`'s result if
       *  that conforms to `S`'s erased type or a `ClassCastException` otherwise.
       */
    

    mapTo[S] 本质上对应于演员表。 Http().singleRequest 产生Future[HttpResponse],而HttpResponse 不能直接转换为String

    要指定一个有意义的逻辑来转换为String,需要进行编组。因此,在您的情况下,您在提供此功能的范围内有一个隐含的 Unmarshaller。这很可能是 Akka-HTTP 预定义集中的默认 stringUnmarshaller。有关这方面的更多信息,请访问docs

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-08
      • 2014-06-19
      • 2019-03-04
      • 1970-01-01
      相关资源
      最近更新 更多