Java+;MongoDB:不必要的连接
创建了一个singleton类来维护MongoDB,但每次初始化时它仍然会创建一个新连接Java+;MongoDB:不必要的连接,java,mongodb,database-connection,Java,Mongodb,Database Connection,创建了一个singleton类来维护MongoDB,但每次初始化时它仍然会创建一个新连接 public class MongoDB { private static MongoDB ourInstance = null; private DB db; private MongoClient mongoClient; public MongoDB() throws UnknownHostException { try{ // To directly connect t
public class MongoDB {
private static MongoDB ourInstance = null;
private DB db;
private MongoClient mongoClient;
public MongoDB() throws UnknownHostException {
try{
// To directly connect to a single MongoDB server (note that this will not auto-discover the primary even
// if it's a member of a replica set:
mongoClient = new MongoClient( "localhost" , 27017 );
db = mongoClient.getDB( "roam" );
}
catch (UnknownHostException e){
System.out.println("Could not establish database connection");
}
}
public DBCursor setCursor (String collectionName, BasicDBObject query, BasicDBObject field){
return db.getCollection(collectionName).find(query, field);
}
public static synchronized MongoDB getInstance() {
if (ourInstance == null) {
try {ourInstance = new MongoDB();}
catch (Exception e) {throw new ExceptionInInitializerError(e);}
}
return ourInstance;
}
protected void finalize (){
this.mongoClient.close();
}
}
当我创建一个web应用程序时,每次刷新带有DB引用的页面时,它都会创建一个新的连接。您是否试图维护
MongoDb
类的singleton实例?我是Java新手,所以可能我做错了什么,但我尝试创建一个singleton MongoDb类,是的……在singleton模式中,类的构造函数必须是private
。。这样就没有外部类能够实例化该类。你能试着让构造函数私有MongoDB()
?哦((这很糟糕,因为我必须从另一个类调用DB,而私有构造函数没有办法这样做。那么我担心,它违反了单例模式。对于单例模式,getInstance()
应该只有这样,外部类才能获得你的单例实例。请检查[this][。就创建多个连接而言,我认为是来自其他类的调用导致了它们。