2017-03-10 51 views
0

我想使用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) 
+0

類似於feature.onComplete? http://doc.akka.io/docs/akka/2.4.4/scala/http/routing-dsl/directives/future-directives/onComplete.html – Ashalynd

+0

如果我更改我的代碼,我得到一個錯誤:錯誤:(166,47)型不匹配; 找到了:Seq [org.mongodb.scala.bson.collection.immutable.Document] required:akka.http.scaladsl.marshalling.ToResponseMarshallable case成功(值)=>完成(值) – bobinshtein

+0

或者您可以使用http: //reactivemongo.org/releases/0.12/documentation/ – cchantep

回答

1

假設的特點是未來的,只是刪除的await做:

complete(feature.map(_.toJson)) 
+0

如果我更改我的代碼,我得到一個錯誤:錯誤:(160,36)值toJson是不是Seq的成員[org.mongodb.scala.Document] complete(future.map(_。toJson())) – bobinshtein

+0

@bobinshtein你還沒有添加解組器。 參見:http://doc.akka.io/docs/akka-http/current/scala/http/common/marshalling.html http://doc.akka.io/docs/akka-http/current/ scala/http/common/json-support.html – jmc

+0

@bobinshtein你的主要問題是你沒有提供編組器。 IT必須將數據類型轉換爲「有線格式」,即可以將請求放入某個數據類型中。 – jmc

相關問題