Yar*_*vaV 2 c++ mongodb c++11 mongo-cxx-driver
我的程序可能连接很少,我需要关闭每个连接.请帮帮我.
#include <iostream>
#include <bsoncxx/builder/stream/document.hpp>
#include <bsoncxx/json.hpp>
#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>
int main(int, char**) {
mongocxx::instance inst{};
mongocxx::client conn{mongocxx::uri{}};
bsoncxx::builder::stream::document document{};
auto collection = conn["testdb"]["testcollection"];
document << "hello" << "world";
collection.insert_one(document.view());
auto cursor = collection.find({});
for (auto&& doc : cursor) {
std::cout << bsoncxx::to_json(doc) << std::endl;
}
need close connection
}
Run Code Online (Sandbox Code Playgroud)
conn.close()或我该如何关闭它?
mongocxx::client 不提供显式断开连接或关闭方法,因为它实际上是另一个内部私有客户端类的包装器,它具有终止连接的析构函数.
如果您查看mongocxx::client声明,它包含一个成员std::unique_ptr<impl> _impl.
这是一个指向实例的唯一指针,该实例mongocxx::client::impl实现了一个析构函数,该析构函数libmongoc::client_destroy(client_t);在客户端对象被销毁时调用.
如果您的应用程序将多次连接/重新连接,您可能有兴趣使用mongocxx::Pool它来管理与MongoDB实例的多个连接,然后您可以在必要时从中获取连接.mongocxx如果您处于多线程应用程序中,这也是推荐使用的方法,因为标准mongocxx:client不是线程安全的.