Akka HTTP 路由 post 实体字符串,以 Future 完成

Akka HTTP route post entity string, complete with Future

我有一个 Akka HTTP 守护进程。假设我想接收一些 JSON 格式的客户端数据并将其异步保存到数据库中。我在 POST 分支中写了一条路线:

path("product") {
  entity(as[String]) { json =>
    val saveFuture: Future[Unit] = Serialization.read[Product](json).save()
    complete("")
  }
}

我发现 complete 可以放入 onSuccess 语句中,例如:

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

但我不明白如何将它们粘在一起。

您可以嵌套指令:

path("product") {
  entity(as[String]) { json =>
    val saveFuture: Future[Unit] = Serialization.read[Product](json).save()
    onSuccess(saveFuture) {
      complete("json was saved")
    }
  }
}