为什么mapTo在Akka HTTP客户端失败?

时间:2017-02-17 09:24:39

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

我有一个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的需要,我试图理解地图和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
  }

1 个答案:

答案 0 :(得分:3)

请参阅以下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

需要使用Umarshalling来指定有意义的逻辑以转换为String。因此,在您的情况下,您在范围内有一个隐式Unmarshaller来提供此功能。这很可能是来自Akka-HTTP预定义集的默认stringUnmarshaller。有关这方面的更多信息,请参阅docs