我在使用mongo cashbash这是我的代码
case class A (id:String,name:String)
class InsertClassA(a:A)
{
def inserA()={
val mongoClient=MongoClient(hostName,port)
//get collection and insert record in mongo
mongoClient.close()
}
}
class UpdateClassA(a:A)
{
def UpdateA()={
val mongoClient=MongoClient(hostName,port)
//get collection and update record in mongo
mongoClient.close()
}
}
class DeleteClassA(a:A)
{
def deleteA()={
val mongoClient=MongoClient(hostName,port)
//get collection and delete record in mongo
mongoClient.close()
}
}
object test extends App {
val a =A("123","bob")
val insert =new InsertClassA(a)
val update =new UpdateClassA(a)
val delete =new DeleteClassA(a)
insert.insertA()
update.UpdateA()
delete.deleteA()
}
我想知道何时关闭mongoConnection?以上方法是否正确?如果不是什么是不浪费任何资源并以良好方式利用mongoCLient实例的正确方法,请指导我
答案 0 :(得分:3)
通常,MongoClient是为长寿命(即应用程序生命周期)量身定制的重量级组件。因此,您应该在开头一次打开它并保留引用。