2
我正在使用mongo cashbah Scala驱动程序我想在我的代码中使用连接池,但我不确定我的代码是否正在使用连接池或者我也读过,我们需要创建MongoClient情况只有一次,再重复使用它,所以我不知道我的代码重用,或每次创建新实例,请指导我在这里是我的代码mongodb scala驱动程序casbah是否自动管理连接池
object MongoFactory {
val log = LoggerFactory.getLogger(this.getClass)
val config = ConfigFactory.load()
var client:MongoClient=null
private var SERVER:ServerAddress = {
val hostName=config.getString("db.hostname")
val port=config.getString("db.port").toInt
new ServerAddress(hostName,port)
}
private var DATABASE:String = config.getString("db.dbname")
def createConnection: MongoClient = {
log.info("server "+SERVER + "DATABASE" +DATABASE)
client=MongoClient(SERVER)
client
}
def getConnection : MongoClient = {
log.debug("In method getConnection")
if(client==null)
{
log.debug("mongoclient instance is null")
client=createConnection
log.debug("mongoclient is {}",client)
log.debug("Leaving method getConnection with returned value {}",client)
client
}
else
{
log.debug("Leaving method getConnection with returned value {}",client)
client
}
}
def getCollection(conn: MongoClient,collectionName:String): MongoCollection = {
conn(DATABASE)(collectionName)
}
def closeConnection(conn: MongoClient) {
conn.close
}
class Abc
{
def readAll()
{
var connection=MongoFactory.getConnection
var collection=MongoFactory.getCollection(connection, "User")
val cursor=collection.find()
while(cursor.hasNext)
{
// here fetching the data from database
}
MongoFactory.closeConnection(connection)
}
def readById()={
var connection=MongoFactory.getConnection
var collection=MongoFactory.getCollection(connection, "User")
val cursor=collection.find(q.get)
while(cursor.hasNext)
{
// here fetching the data from database
}
MongoFactory.closeConnection(connection)
}
}
object test extends App {
MongoFactory.getConnection
val abc=new Abc()
abc.readAll()
abc.readById()
}
我有一个关于上面的代码
一些问题这段代码是使用conn挠度池
这段代码重用mongoClient实例或它的每一次
我是否需要关闭每个查询后连接,如果不是当 我应该关闭连接
请指导我
UPDATE
我做了如下修改代码
object MongoFactory {
val log = LoggerFactory.getLogger(this.getClass)
val config = ConfigFactory.load()
var client:MongoClient=null
private var SERVER:ServerAddress = {
val hostName=config.getString("db.hostname")
val port=config.getString("db.port").toInt
new ServerAddress(hostName,port)
}
private var DATABASE:String = config.getString("db.dbname")
val connectionMongo = MongoConnection(SERVER)
val collectionMongo = connectionMongo(DATABASE)("artGroup")
}
class Abc
{
def readAll()
{
val cursor=collectionMongo.find()
while(cursor.hasNext)
{
// here fetching the data from database
}
}
def readById()={
val cursor=collectionMongo.find(q.get)
while(cursor.hasNext)
{
// here fetching the data from database
}
}
}
object test extends App {
val abc=new Abc()
abc.readAll()
abc.readById()
}
做这个更新的代码被重用蒙戈连接或它创建一个新的实例每次请指导我
你可以通过例子来解释它会很好,非常有帮助 – swaheed
现在看起来不错 – tkachuko