我有返回字符串,如以下所示的阿卡HTTP服務:爲什麼在Akka HTTP客戶端中mapTo失敗?
val route1: Route = {
path("hello") {
get{
complete{
println("Inside r1")
"You just accessed hello"
}
}
}
}
我有嘗試訪問此路線的阿卡HTTP客戶端。但下面的代碼失敗:
val future1 = Http()
.singleRequest(
HttpRequest(method = HttpMethods.GET,
uri = "http://localhost:8187/hello")).mapTo[String]
future1.onSuccess({
case y:String=>println(y)
})
我根本沒有輸出。但是,如果我用的解組,而不是用flatMap,我得到的輸出:
val future1:Future[String] = Http()
.singleRequest(
HttpRequest(method = HttpMethods.GET,
uri = "http://localhost:8187/hello")).flatMap(resp => Unmarshal(resp).to[String])
爲什麼mapTo失敗這裏,爲什麼我需要flatMap與解組?
編輯:
我明白了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
}