有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

mongodb java MongoClient何时建立到DB的连接?

我正在使用JavaMongo驱动程序3.2,我正试图弄清楚什么应该有多个实例,什么应该在应用程序中持久化

例如,MongoClient说这个应用程序应该只有一个实例。它还说它建立了一个连接池。这很好。这些联系实际上是什么时候建立的?我想确保我能有效地使用游泳池

那么,当我执行MongoClient#getDataBase时,是否与数据库建立了连接MongoDatabase#getCollection?或者在我对集合本身执行操作时,例如。找到了吗

应该省掉什么?我应该有多个数据库实例吗?收藏?还是仅仅是客户

我主要是想确保我不会将自己限制在一个连接上,但也不会不必要地向数据库发送垃圾邮件


共 (1) 个答案

  1. # 1 楼答案

    每个应用程序只需一次实例就可以了MongoDB Driver Quick Tour - Java似乎很清楚。编辑:我对这篇文章的理解是,当你调用MongoClient.getDB();时,就是你正在连接的时候,要确保通过他们的源代码进行解析,如果可以看到确切的时刻。编辑2:添加了到MongoDB Java驱动程序的链接,这里是MongoDB Driver,特别是您要检查的类是MongoClient,它扩展了Mongo.class,这是.getDB();所在的位置;在这个方法中,他们检查数据库缓存,如果没有,他们创建一个新的DB.class实例。在运行完代码后,它会出现在Mongo.class构造函数中,因此当您调用new MongoClient();时,它们会调用connector.start()

     public Mongo( ServerAddress addr , MongoOptions options )
            throws MongoException {
            _addr = addr;
            _addrs = null;
            _options = options;
            _applyMongoOptions();
            _connector = new DBTCPConnector( this , _addr );
            _connector.start();
            _cleaner = new DBCleanerThread();
            _cleaner.start();
        }
    

    从他们的页面

    // 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 mongoClient = new MongoClient();
    // or
    MongoClient mongoClient = new MongoClient( "localhost" );
    // or
    MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
    // or, to connect to a replica set, with auto-discovery of the primary, supply a seed list of members
    MongoClient mongoClient = new MongoClient(Arrays.asList(new ServerAddress("localhost", 27017),
                                          new ServerAddress("localhost", 27018),
                                          new ServerAddress("localhost", 27019)));
    
    DB db = mongoClient.getDB( "mydb" );
    

    At this point, the db object will be a connection to a MongoDB server for the specified database. With it, you can do further operations.

    The MongoClient class is designed to be thread safe and shared among threads. Typically you create only 1 instance for a given database cluster and use it across your application.

    important

    When creating many MongoClient instances:

    All resource usage limits (max connections, etc) apply per MongoClient instance
    To dispose of an instance, make sure you call MongoClient.close() to clean up resources