使 mongoClient object/any 对象在整个应用程序中可用
make mongoClient object/any object available across the application
您好,我正在使用 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()
。只会使用一个对象。
您好,我正在使用 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()
。只会使用一个对象。