2017-02-17 7 views
1

나는 다음과 같이 문자열을 반환하는 Akka HTTP 서비스가 있습니다. 그러나 아래 코드는 실패합니다.왜 Akka HTTP 클라이언트에서 mapTo가 실패합니까?</p> <pre><code>val route1: Route = { path("hello") { get{ complete{ println("Inside r1") "You just accessed hello" } } } } </code></pre> <p>나는이 경로에 액세스하려고 Akka 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과 비 정렬 화는 필요합니까?

편집 :

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] 
    } 
: 나는 Unmarhsal의 필요성을 이해하고 내가지도 및 예를 들어

flatMap의 차이를 이해하려고 노력하고

, 아래의 코드는 나에게 예상대로 결과를 제공

그러나 맵으로 대체하려고하면 다음과 같이 출력됩니다. 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 
    } 
,363,210

답변

3

/** 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] 아래 mapTo의 문서를 참조하십시오 본질적 캐스트에 해당합니다. Http().singleRequestFuture[HttpResponse]을 생성하고, HttpResponseString으로 퉁명스럽게 캐스팅 될 수 없다.

String으로 변환하는 의미있는 논리를 지정하기 위해 언 마샬링이 필요합니다. 따라서 귀하의 경우에는 암시 적 범위 인 Unmarshaller이 있습니다. 그리고 이것은 Akka-HTTP 사전 정의 된 세트의 기본값 인 stringUnmarshaller 일 가능성이 큽니다. 이에 대한 자세한 내용은 docs에서 확인할 수 있습니다.