[英]Mongocxx change_stream callback
我有一個正在監視 mongo db 的進程,並且需要在表發生更改時得到通知。
處理這個問題的最合乎邏輯的方法似乎是通過一個帶有回調的 change_stream 來執行,該回調在某些事情發生變化時執行——也就是說,與 JavaScript 中的“監視”函數相同。
查看文檔,我看到 changestream 對象具有迭代器,但我沒有看到回調選項。 有沒有辦法處理這個問題和\/或有什么好的例子可以利用?
Mongocxx 沒有回調 API,但由於更改流 API 具有阻塞調用,因此您可以使用一個類實現自己的回調系統,該類會產生一個用於觀察的線程,然后在發生某些事情時調用回調。 下面的示例代碼:
#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>
#include <bsoncxx/document/view.hpp>
// STD
#include <iostream>
#include <string>
#include <thread>
#include <functional>
#include <chrono>
class MongoWatcher
{
public:
MongoWatcher(std::function<void(std::string)> callback);
private:
std::thread* m_changesThread;
std::function<void(std::string)> m_changeCallback;
void watchCollection();
};
MongoWatcher::MongoWatcher(std::function<void(std::string)> callback)
{
// Asssuming Mongocxx instance has been created by invoking code
m_changeCallback = callback;
m_changesThread = new std::thread([this](){watchCollection();});
}
void MongoWatcher::watchCollection()
{
mongocxx::uri uri("mongodb://localhost:27017");
mongocxx::client client = mongocxx::client(uri);
mongocxx::database db = client["db"];
mongocxx::collection collection = db["col"];
while (true) // Loop forever
{
try
{
mongocxx::options::change_stream options;
options.full_document("updateLookup");
const std::chrono::milliseconds await_time{1000};
options.max_await_time(await_time);
mongocxx::change_stream streamChanges = collection.watch(options);
for (const bsoncxx::document::view& event : streamChanges)
{
bsoncxx::document::view view = event;
bsoncxx::document::element element = view["operationType"];
bsoncxx::types::b_utf8 utf = element.get_utf8();
std::string operationType = utf.value.data();
m_changeCallback(operationType);
}
}
catch (const std::exception& e)
{
std::cerr << "MongoDB watcher caught exception: " << e.what() << std::endl;
}
// Take a short pause before checking for changes again
std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.