Mongo connection leak with morphia

ぃ、小莉子 提交于 2019-12-06 01:33:05

You can create a singleton Datastore object

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;
}
}

and now you can reuse the same Datastore object in your application

 Datastore datastore = MongoDBHelper.INSTANCE.getDatastore()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!