gpt4 book ai didi

java - Mongo 连接泄漏与吗啡

转载 作者:可可西里 更新时间:2023-11-01 09:24:44 26 4
gpt4 key购买 nike

我有一个带有 static Mongo = new Mongo()Morphia morphia = new Morphia() 对象的 Servlet。每次调用 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 的连接的正确方法是什么?连接真正泄漏的地方是什么?谢谢。

最佳答案

您可以创建一个单例 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()

关于java - Mongo 连接泄漏与吗啡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21580147/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com