我正在编写一个简单的基于 scala 的脚本,该脚本应该将一些数据插入 Mongo 集合中。问题是,该脚本在 mongo 完成其任务之前退出。考虑以下脚本,处理该问题的惯用/最佳方法是什么:
#!/usr/bin/env scalas
/***
scalaVersion := "2.12.2"
libraryDependencies ++= {
Seq(
"org.mongodb.scala" %% "mongo-scala-driver" % "2.1.0"
)
}
*/
import org.mongodb.scala._
val mongoClient: MongoClient = MongoClient("mongodb://localhost")
val database: MongoDatabase = mongoClient.getDatabase("dev")
val doc: Document = Document("name" -> "MongoDB", "type" -> "database",
"count" -> 1, "info" -> Document("x" -> 203, "y" -> 102))
val collection: MongoCollection[Document] = database.getCollection("test")
val subscription = new Observer[Completed] {
override def onNext(result: Completed): Unit = println("Inserted")
override def onError(e: Throwable): Unit = println("Failed"+e.toString)
override def onComplete(): Unit = println("Completed")
}
collection.insertOne(doc).subscribe(subscription)
上面的脚本执行时会产生以下错误:
com.mongodb.MongoInterruptedException: Interrupted acquiring a permit to retrieve an item from the pool
但是,如果我添加Thread.sleep(3000)
最后它完成得很好。
我建议使用 Promise 对象来通知异步作业的完成。
http://www.scala-lang.org/api/2.12.1/scala/concurrent/Promise.html http://www.scala-lang.org/api/2.12.1/scala/concurrent/Promise.html
异步作业完成后或超时后,程序将退出。
val promise = Promise[Boolean]
...
override def onError(e: Throwable): Unit = {
println("Failed"+e.toString)
promise.success(false)
}
override def onComplete(): Unit = {
println("Completed")
promise.success(true)
}
val future = promise.future
Await.result(future, Duration(10, java.util.concurrent.TimeUnit.SECONDS))
//after completion, the program would exit.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)