您好我正在使用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.
所以,我想让每个用户都可以使用这个对象。我怎么能这样做?
答案 0 :(得分:1)
最好的方法是使用Singleton设计模式。这是代码 -
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()
。只会使用一个对象。