我有Servlet
个static Mongo = new Mongo()
和Morphia morphia = new Morphia()
个对象。每次调用GET
时,我都会执行以下操作:
doGet(...){
...
datastore = morphia.createDatastore(mongo, dbName);
...
}
我没有关闭datastore
,因为没有紧密的方法。每次调用servlet时,mongo中使用的连接数都会增长:
{ "current" : 113, "available" : 706, "totalCreated" : NumberLong(122) }
> db.serverStatus().connections { "current" : 115, "available" : 704, "totalCreated" : NumberLong(124) }
> db.serverStatus().connections { "current" : 116, "available" : 703, "totalCreated" : NumberLong(125) }
> db.serverStatus().connections { "current" : 121, "available" : 698, "totalCreated" : NumberLong(130) }
> db.serverStatus().connections { "current" : 122, "available" : 697, "totalCreated" : NumberLong(131) }
> db.serverStatus().connections { "current" : 128, "available" : 691, "totalCreated" : NumberLong(137) }
关闭与mongo和morphia的连接以及连接真正泄漏的正确方法是什么?感谢。
答案 0 :(得分:6)
您可以创建singleton
Datastore
对象
public enum MongoDBHelper { // the best way to implement singletons, due to the author of Effective Java
INSTANCE;
private DB db;
private Datastore datastore;
private final String SERVER_URL = "...";
private final int SERVER_PORT = ...;
private final String USERNAME= "...";
private final String PASSWORD = "...";
private final String DATABASE_NAME = "...";
private MongoDBHelper() {
try {
MongoClient mongoClient = new MongoClient(SERVER_URL, SERVER_PORT);
this.db = mongoClient.getDB(DATABASE_NAME);
this.db.authenticate(USERNAME,PASSWORD.toCharArray());
Morphia morphia = new Morphia();
this.datastore = morphia.createDatastore(mongoClient, DATABASE_NAME);
morphia.mapPackage("package");
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
public DB getDB() {
return this.db;
}
public Datastore getDatastore() {
return this.datastore;
}
}
现在您可以在应用程序中重用相同的Datastore
对象
Datastore datastore = MongoDBHelper.INSTANCE.getDatastore()