问题描述
我正在尝试设计一个Mongo Db连接类,我将MongoClient作为静态设置。
I am trying to design a Mongo Db connection class where I am maintaning MongoClient as static.
private static MongoClient client = null;
public static DB connectToMongo() throws Exception {
if (null != client) {
return client.getDB(DBNAME);
}
client = new MongoClient(HOST,PORT);
return client.getDB(DBNAME);
}
我的整个网络应用程序使用上述方法连接到Mongo,如下所示: / p>
My whole web application uses the above method to connect to Mongo as follows:
db = MongoDBConnection.connectToMongo();
collection = db.getCollection("collectionName");
执行数据库操作后,我从不调用MongoClient的关闭连接。连接类总是会返回相同的MongoClient实例,它永远不会被关闭。我唯一关闭的是游标。
After performing DB operations I never call the close connection for MongoClient. The connection class would always return the same instance of MongoClient which is never closed.The only thing I close is cursors.
- 每次查询数据库时是否需要关闭MongoClient?
我的上述设计是否有效?
- Is it necessary to close the MongoClient every time we query the database?Is my above design valid?
推荐答案
你一定要每次查询数据库时都不要关闭 MongoClient 。 MongoClient维护一个连接池,设置起来相对昂贵,因此您需要在Web应用程序的整个生命周期内重用MongoClient实例。
You should definitely not close the MongoClient every time you query the database. The MongoClient maintains a connection pool, which is relatively expensive to set up, so you'll want to re-use the MongoClient instance across the lifetime of your web application.
还有几点要指出:
- connectToMongo方法中存在竞争条件。您需要同步对该方法的访问,以确保最多创建一个MongoClient实例。
- 如果您在未首先重新启动应用程序服务器的情况下重新部署Web应用程序,则必须确保在Web应用程序关闭时关闭MongoClient。例如,您可以使用ServletContextListener执行此操作。
这篇关于关闭MongoDB Java连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!