mongodb java MongoClient何时建立到DB的连接?
我正在使用JavaMongo驱动程序3.2,我正试图弄清楚什么应该有多个实例,什么应该在应用程序中持久化
例如,MongoClient
说这个应用程序应该只有一个实例。它还说它建立了一个连接池。这很好。这些联系实际上是什么时候建立的?我想确保我能有效地使用游泳池
那么,当我执行MongoClient#getDataBase
时,是否与数据库建立了连接MongoDatabase#getCollection
?或者在我对集合本身执行操作时,例如。找到了吗
应该省掉什么?我应该有多个数据库实例吗?收藏?还是仅仅是客户
我主要是想确保我不会将自己限制在一个连接上,但也不会不必要地向数据库发送垃圾邮件
# 1 楼答案
每个应用程序只需一次实例就可以了MongoDB Driver Quick Tour - Java似乎很清楚。编辑:我对这篇文章的理解是,当你调用
MongoClient.getDB();
时,就是你正在连接的时候,要确保通过他们的源代码进行解析,如果可以看到确切的时刻。编辑2:添加了到MongoDB Java驱动程序的链接,这里是MongoDB Driver,特别是您要检查的类是MongoClient,它扩展了Mongo.class
,这是.getDB();
所在的位置;在这个方法中,他们检查数据库缓存,如果没有,他们创建一个新的DB.class
实例。在运行完代码后,它会出现在Mongo.class
构造函数中,因此当您调用new MongoClient();
时,它们会调用connector.start()
从他们的页面