在应用程序上使Mongoclient对象/任何可用的对象



你好,我正在与mongodb java驱动程序一起工作。在他们的文档中,他们提到,

The MongoClient class is designed to be thread safe and shared among threads.
Typically you create only 1 instance for a given database cluster and use it across 
your application.

所以,我想让每个用户可用此对象。我该怎么做?

做到这一点的最佳方法是使用单身设计模式。这是代码 -

public class MongoDBManager {
    public MongoClient mongoClient = null;
    String host = "127.0.0.1";
    static MongoDBManager mongo=new MongoDBManager();
    private MongoDBManager() {
        try {
            mongoClient = new MongoClient( host , 27017);
            } catch (UnknownHostException e) {
            System.err.println("Connection errors");
            e.printStackTrace();
        }
    }
    public static MongoDBManager getInstance(){
        return mongo;
    }
}

只要您需要连接时,只能致电MongoDBManager.getInstance()。只有一个对象。

相关内容

最新更新