我的MongoDB DAO应该请求唯一的DB对象吗?

时间:2021-10-07 12:36:37

I'm using the standard MongoDB Java driver to roll my own DAOs. I'm aware that all of my DAOs can share the same Mongo instance, but should all of my DAOs accessing the same database share the same DB object or are there good reasons for a new DB object to be requested or each?

我正在使用标准的MongoDB Java驱动程序来滚动我自己的DAO。我知道我的所有DAO都可以共享同一个Mongo实例,但是我访问同一个数据库的所有DAO是否共享相同的数据库对象,或者是否有充分理由要求新的DB对象或每个?

Thanks!

谢谢!

2 个解决方案

#1


2  

You can use shared instances of the Mongo class, the DB class and the DBCollection class if that proves to be practical for you. Whether or not you want to from a design perspective is up to you. I'd definitely use Mongo instances as singletons since they're relatively heavy weight (have their own thread pool etc.)

您可以使用Mongo类,DB类和DBCollection类的共享实例,如果这对您来说是实用的。从设计的角度来看,您是否想要取决于您自己。我肯定会使用Mongo实例作为单例,因为它们的权重相对较大(有自己的线程池等)

#2


1  

The "good reason" to share the Mongo object is built-in connection pooling. If it's not practical to share your Mongo object instance between DAOs, then that's a good reason (in my opinion), to create new instances. If it is practical, then you should share it.

共享Mongo对象的“好理由”是内置连接池。如果在DAO之间共享Mongo对象实例是不切实际的,那么(在我看来)创建新实例是一个很好的理由。如果它是实用的,那么你应该分享它。

Remember that you should use .close() when you're done using a Mongo instance, to prevent leaving open connections.

请记住,在使用Mongo实例时应使用.close(),以防止保持打开连接。

#1


2  

You can use shared instances of the Mongo class, the DB class and the DBCollection class if that proves to be practical for you. Whether or not you want to from a design perspective is up to you. I'd definitely use Mongo instances as singletons since they're relatively heavy weight (have their own thread pool etc.)

您可以使用Mongo类,DB类和DBCollection类的共享实例,如果这对您来说是实用的。从设计的角度来看,您是否想要取决于您自己。我肯定会使用Mongo实例作为单例,因为它们的权重相对较大(有自己的线程池等)

#2


1  

The "good reason" to share the Mongo object is built-in connection pooling. If it's not practical to share your Mongo object instance between DAOs, then that's a good reason (in my opinion), to create new instances. If it is practical, then you should share it.

共享Mongo对象的“好理由”是内置连接池。如果在DAO之间共享Mongo对象实例是不切实际的,那么(在我看来)创建新实例是一个很好的理由。如果它是实用的,那么你应该分享它。

Remember that you should use .close() when you're done using a Mongo instance, to prevent leaving open connections.

请记住,在使用Mongo实例时应使用.close(),以防止保持打开连接。