【发布时间】:2017-08-01 10:32:48
【问题描述】:
我想使用akka-http 和新的mongo-scala-driver 进行休息服务。
此代码有效
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"
更新
如果我更改代码:
complete(future.map(_.toJson()))
我收到一个错误:
Error:(160, 36) value toJson is not a member of Seq[org.mongodb.scala.Document]
complete(future.map(_.toJson()))
更新
如果我更改代码:
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 的东西? doc.akka.io/docs/akka/2.4.4/scala/http/routing-dsl/directives/…
-
如果我更改我的代码,我得到一个错误:Error:(166, 47) type mismatch;找到:Seq[org.mongodb.scala.bson.collection.immutable.Document] 需要:akka.http.scaladsl.marshalling.ToResponseMarshallable case Success(value) => complete(value)
-
好的,谢谢,不过我想用官方的mongo驱动...
标签: mongodb scala akka future akka-http