我正在使用mongo cashbah Scala驱动程序我想在我的代码中使用连接池,但我不确定我的代码是否使用连接池或者我也读过我们只需要创建一次MongoClient实例并重新使用它我不确定我的代码是重复使用它还是每次创建一个新实例请在这里指导我是我的代码
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()
}
我对上述代码有一些疑问
此代码是否正在使用连接池
此代码是否重用mongoClient实例或其创建新实例 每次实例
我是否需要在每次查询后关闭连接,如果不是 我应该关闭连接
请指导我
更新
我对代码进行了以下更改
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()
}
这个更新的代码是重新使用mongo连接还是每次都引导我创建一个新实例
答案 0 :(得分:2)
请参阅此question。因此,无论何时创建MongoConnection
,实际上都会创建连接池。
关于您的特定代码:每次要获取记录时,您都在创建MongoConnection
。将其分配给val
,将其移至上一级并始终使用它。当应用程序停止时关闭它。