在Akka HTTP中提取未来

时间:2017-02-16 07:37:51

标签: scala akka akka-http

考虑以下代码:

class TestActor extends Actor {
  def receive = {

    case "hello" => 
      sender ! Future {
        "Sample future result"
      }
  }
}

我定义了以下路线:

def r5: Route = {
    pathPrefix("check") {
      onSuccess(system.actorOf(Props[TestActor]).ask("hello")) {
        successResult =>
          complete {
            "The result is " + successResult
          }
      }
    }
  }

当我访问路线时,我得到的输出为The result is Success(Sample future result),而我预期它为The result is Sample future result。来自关于onSuccess的文档here

  

评估其类型Future [T]的参数,一旦Future有   已成功完成,将其结果提取为T类型的值   并将其传递到内部路线。

,给出的例子是:

val route =
  path("success") {
    onSuccess(Future { "Ok" }) { extraction =>
      complete(extraction)
    }
  }

那我哪里错了?

2 个答案:

答案 0 :(得分:2)

ask返回Future[T]receive中的模式匹配处理程序将其包含在另外的Future[T]中,因此您获得了Future[Future[String]]

如果您只想检索T,请从Future中移除TestActor

case class TestResult(s: String)
case "hello" => 
  sender ! TestResult("Sample future result")

答案 1 :(得分:0)

如果使用ask是不可避免的,那么在r5路线中的onComplete中你需要打开未来两次,因为你收到了Future [Future [String]]。

完成后将打开一个,你可以

  def r5: Route = {
    pathPrefix("check") {
      onSuccess(system.actorOf(Props[TestActor]).ask("hello")) {
        successResult => { 
                 successResult.Oncomplete {
                      case Success(res) => {
                                complete {
                                      "The result is " + res //res will have Sample Future Result }
                      case Failure(ex) => complete("Some Error Occured")
        
      }
    }
  }