我想使用akka-http
和新的mongo-scala-driver
作爲我的休息服務。使用akka-http和mongo-scala驅動程序
此代碼工作
val routes = {
pathPrefix("info") {
pathEndOrSingleSlash {
get {
val mongoClient: MongoClient = MongoClient("mongodb://localhost:27017,localhost:27018,localhost:27019/?replicaSet=rs0")
val database: MongoDatabase = mongoClient.getDatabase("test")
val collection: MongoCollection[Document] = database.getCollection("test")
val future = collection.find().limit(10).toFuture()
val list = Await.result(future, Duration(10, TimeUnit.SECONDS))
complete(list.map(_.toJson()))
}
}
}
}
但我想除去保護代碼Await.result
寫異步的。
我該怎麼辦?由於
build.sbt:
scalaVersion := "2.12.1"
"org.mongodb.scala" %% "mongo-scala-driver" % "1.2.1"
"com.typesafe.akka" %% "akka-http-core" % "10.0.4"
"com.typesafe.akka" %% "akka-http" % "10.0.4"
UPDATE
如果我改變我的代碼:
complete(future.map(_.toJson()))
我得到一個錯誤:
Error:(160, 36) value toJson is not a member of Seq[org.mongodb.scala.Document]
complete(future.map(_.toJson()))
UPDATE
如果我改變我的代碼:
onComplete(future) {
case Success(value) => complete(value)
case Failure(ex) => complete((InternalServerError, s"An error occurred: ${ex.getMessage}"))
}
我得到連接錯誤:
Error:(166, 47) type mismatch;
found : Seq[org.mongodb.scala.bson.collection.immutable.Document]
required: akka.http.scaladsl.marshalling.ToResponseMarshallable
case Success(value) => complete(value)
類似於feature.onComplete? http://doc.akka.io/docs/akka/2.4.4/scala/http/routing-dsl/directives/future-directives/onComplete.html – Ashalynd
如果我更改我的代碼,我得到一個錯誤:錯誤:(166,47)型不匹配; 找到了:Seq [org.mongodb.scala.bson.collection.immutable.Document] required:akka.http.scaladsl.marshalling.ToResponseMarshallable case成功(值)=>完成(值) – bobinshtein
或者您可以使用http: //reactivemongo.org/releases/0.12/documentation/ – cchantep