在一个应用程序中哪个应该是单例?MongoClient 或 MongoDatabase 或 MongoCollection? [英] Which should be singleton in one application? MongoClient or MongoDatabase or MongoCollection?

查看:144
本文介绍了在一个应用程序中哪个应该是单例?MongoClient 或 MongoDatabase 或 MongoCollection?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

<块引用>

MongoClient 实例实际上代表了一个到数据库的连接池;即使有多个线程,您也只需要 MongoClient 类的一个实例.

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

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

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

解决方案

MongoClient 通常应该是单例.您的引述提到了这一点

<块引用>

MongoClient 实例实际上代表了一个连接池数据库;你只需要 MongoClient 类的一个实例即使有多个线程.

它还在 javadocs 中提到了这一点::><块引用>

具有内部连接池的 MongoDB 客户端.对于大多数应用程序,您应该为整个应用程序提供一个 MongoClient 实例JVM.

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

As mentioned in the docs: 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.

Using codes below can get the collection(just like 'table' in the RDMS):

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

I found these code always return new instances, so,how about making the MongoDatabase or MongoCollection as the Singleton in my applicaiton?

解决方案

MongoClient should typically be the singleton. Your quote mentions this

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.

It also mentions this in the javadocs:

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

It does not make sense to have MongoDatabase or MongoCollection as singletons mainly (there are other reasons) because the underlying connection can get stale, which requires some coding to refresh a singleton MongoDatabase or singleton MongoCollection.

这篇关于在一个应用程序中哪个应该是单例?MongoClient 或 MongoDatabase 或 MongoCollection?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆