【问题标题】:akka-http complete response with different typesakka-http 不同类型的完整响应
【发布时间】:2017-01-04 16:02:38
【问题描述】:

如何根据未来的响应完成不同类型的 akka-http 响应? 我正在尝试做类似的事情

implicit val textFormat = jsonFormat1(Text.apply)
implicit val userFormat = jsonFormat2(User.apply)
 path(Segment) { id =>
              get {
                complete {
                  (fooActor ? GetUser(id)).map {
                    case n: NotFound => Text("Not Found")
                    case u: User => u
                  }
                }

              }
            }

但我得到了

type mismatch , expected: ToResponseMarshable , actual Futue[Product with Serializable ]

【问题讨论】:

  • 我认为这是因为它不知道如何解组自定义 User 类。你必须定义一个。请参阅 Unmarshaller 部分和此页面外的链接:doc.akka.io/docs/akka-http/current/java/http/routing-dsl/…
  • @brian 我不这么认为,因为如果我在两种情况下都回复用户,那没关系,也不是我在用户范围内有解组器

标签: scala akka-http


【解决方案1】:

您可以使用onComplete 指令:

get {
  path(Segment) { id =>
    onComplete(fooActor ? GetUser(id)) {
      case Success(actorResponse) => actorResponse match {
        case _ : NotFound => complete(StatusCodes.NotFound,"Not Found")
        case u : User => complete(StatusCodes.OK, u)
      }
      case Failure(ex) => complete(StatusCodes.InternalServerError, "bad actor")
    }
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-13
    相关资源
    最近更新 更多