gpt4 book ai didi

java - 在一个应用程序中哪个应该是单例? MongoClient 或 MongoDatabase 或 MongoCollection?

转载 作者:可可西里 更新时间:2023-11-01 10:42:00 26 4
gpt4 key购买 nike

如文档中所述: http://mongodb.github.io/mongo-java-driver/3.3/driver/getting-started/quick-tour/

The MongoClient instance actually represents a pool of connections to the database; you will only need one instance of class MongoClient even with multiple threads.

使用下面的代码可以获得集合(就像RDMS中的'table'):

MongoDatabase database = mongoClient.getDatabase("mydb");
MongoCollection<Document> collection = database.getCollection("test");

我发现这些代码总是返回新实例,那么,在我的应用程序中将 MongoDatabaseMongoCollection 作为单例怎么样?

最佳答案

MongoClient 通常应该是单例。你的报价提到了这一点

The MongoClient instance actually represents a pool of connections to the database; you will only need one instance of class MongoClient even with multiple threads.

它还在 javadocs 中提到了这一点:

A MongoDB client with internal connection pooling. For most applications, you should have one MongoClient instance for the entire JVM.

主要将 MongoDatabaseMongoCollection 作为单例(还有其他原因)是没有意义的,因为底层连接可能会失效,这需要一些编码来刷新单例 MongoDatabase 或单例 MongoCollection。

关于java - 在一个应用程序中哪个应该是单例? MongoClient 或 MongoDatabase 或 MongoCollection?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39219990/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com