[英]MongoCxx 3.1.0 How can I close connection?
我有可能没有几个连接的程序,我需要关闭每个连接。 请帮帮我。
#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
}
conn.close()或如何关闭它?
mongocxx::client
不提供显式的disconnect或close方法,因为它实际上是另一个内部私有客户端类的包装,该类具有终止连接的析构函数。
如果查看mongocxx::client
声明,则其中包含成员std::unique_ptr<impl> _impl
。
这是指向mongocxx::client::impl
实例的唯一指针,该实例实现了一个调用libmongoc::client_destroy(client_t);
的析构函数libmongoc::client_destroy(client_t);
当客户端对象被销毁时。
如果您的应用程序将要进行多次连接/重新连接,您可能会对使用mongocxx::Pool
感兴趣,该服务器管理与MongoDB实例的许多连接,然后在必要时可以从中获取连接。 如果您在多线程应用程序中,这也是推荐使用mongocxx
方法,因为标准的mongocxx:client
不是线程安全的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.