本文介绍了Java MongoDB 连接池的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 MongoDB 中使用 Java.在这里,我在每个方法中打开 MongoClient.我只需要在整个课程中打开它一次并关闭它一次.

I am using Java with MongoDB. Here I am opening MongoClient in each method. I only need to open it once through out the class and close it once.

public class A
{
    public String name()
    {
        MongoClient mongo = new MongoClient(host, port);
        DB db = mongo.getDB(database);
        DBCollection coll = db.getCollection(collection);

        BasicDBObject doc = new BasicDBObject("john", e.getName())
    }

    public String age()
    {
        MongoClient mongo = new MongoClient(host, port);
        DB db = mongo.getDB(database);
        DBCollection coll = db.getCollection(collection);

        BasicDBObject doc = new BasicDBObject("age", e.getAge())
    }
}

推荐答案

您可以使用单例模式来保证每个应用程序只有一个 MongoClient 类的实例.一旦您获得MongoClient 的实例,您就可以执行您的操作,而无需像MongoClient.close 那样显式管理操作,因为该对象会自动管理连接池.

You can use a Singleton pattern to guarantee only one instance of MongoClient class per application. Once you obtain the instance of MongoClient, you can perform your operations and don't need to explicitly manage operations like MongoClient.close, as this object manages connection pooling automatically.

在您的示例中,您可以在静态变量中初始化 MongoClient.

In your example, you can initialize the MongoClient in a static variable.

这篇关于Java MongoDB 连接池的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 06:04
查看更多