创建了一个单例类来维护 MongoDB,但每次初始化时它仍然会创建一个新连接。
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 应用程序时,它会在每次刷新带有数据库引用的页面时创建一个新连接。