我正在使用Spring Data for Mongodb,有时我用这种方式使用java驱动程序:
DBCollection mycoll = mongoOperations.getCollection("mycoll");使集合mycoll静态并通过Singleton实例化它是否有意义?
I'm using Spring Data for Mongodb and sometimes I use the java driver this way :
DBCollection mycoll = mongoOperations.getCollection("mycoll");Does it make sense to make the collection mycoll static and instantiate it through a Singleton?
最满意答案
你不需要一个Singleton,如果你只有一个实例而你需要管理那个实例,你只需要一个Singleton,请参阅这篇文章 。 Java Mongo驱动程序的源代码显示MongoDB集合不是这种情况。 'getCollection`方法仅验证集合是否存在于collectionCache(散列映射)中并且不执行任何数据库操作,因此多次调用它的开销很小。 请参阅以下https://github.com/mongodb/mongo-java-driver中的相关代码段
/** * Gets a collection with a given name. * * @param name the name of the collection to return * @return the collection */ public DBCollection getCollection(final String name) { DBCollection collection = collectionCache.get(name); if (collection != null) { return collection; }You do not need a Singleton for this, you only need a Singleton if you can only ever have one instance and you need to manage that instance, see this post. The source code of the Java Mongo driver shows this is not the case for MongoDB collections. The 'getCollection` method only verifies if the collection exists in the collectionCache (a hashmap) and does not perform any database operations, so the overhead of calling it multiple times is minimal. See below the relevant code snippet from https://github.com/mongodb/mongo-java-driver
/** * Gets a collection with a given name. * * @param name the name of the collection to return * @return the collection */ public DBCollection getCollection(final String name) { DBCollection collection = collectionCache.get(name); if (collection != null) { return collection; }更多推荐
发布评论