0
import scala.collection.JavaConverters._
import scala.concurrent.Await
import scala.concurrent.Future
import scala.concurrent.duration._
import scala.io._
import org.json.JSONObject
import org.json4s.native.Serialization._
import org.mongodb.scala._
import org.mongodb.scala.model.Filters._
import org.mongodb.scala.model.Updates._
import org.mongodb.scala.Document._
import com.mongodb.MongoCredential
import com.mongodb.async.client.MongoClientSettings
import com.mongodb.connection.ClusterSettings
import com.mongodb.client.model.UpdateOptions
import com.mongodb.client.result.UpdateResult
import scala.concurrent.ExecutionContext
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration.Duration
import scala.concurrent._
import scala.util._
object Async {
def main(args: Array[String]): Unit =
{
var mongoClient: MongoClient = null
val credential: MongoCredential = MongoCredential.createScramSha1Credential("user", "database", "password".toArray)
val clusterSettings: ClusterSettings = ClusterSettings.builder().hosts(List(new ServerAddress("localhost:27017")).asJava).build()
val settings: MongoClientSettings = MongoClientSettings.builder().codecRegistry(MongoClient.DEFAULT_CODEC_REGISTRY).clusterSettings(clusterSettings).credentialList(List(credential).asJava).build()
mongoClient = MongoClient(settings)
val db: MongoDatabase = mongoClient.getDatabase("database")
var collection: MongoCollection[Document] = db.getCollection("collectionName")
var output : Document = Document()
var query: Document = Document()
var projection: Document = Document()
output = find(query, projection, collection)
println(output)
}
def find(query: Document, projection: Document, collectionName : MongoCollection[Document]) : Document = {
var previousDoc : Document = Document()
var future = collectionName.find(equal("_id", query)).projection(projection).toFuture()
collectionName.find(equal("_id", query)).projection(projection).subscribe(
(data: Document) => { previousDoc = data },
(error: Throwable) => println(s"Query failed: ${error.getMessage}"),
() => println("Done")
)
Await.result(future, Duration(100000, MILLISECONDS))
previousDoc
}
}
私はmongodbでfindオペレーションを実行しました。ここではスカラーを使用したコードです。上記のコードの実行はブロックされないので、プロセスはmongodbからデータを取得する前に終了します。私は、AwaitとThread.sleep関数を使用せずにmongodb操作を実行している間、ノンブロッキングを制御する方法を知りたい。Scala Mongodb 3.0ドライバで非同期的にfindオペレーションを実行する方法AwaitとThreadを指定せずに