如何监听 MongoDB 集合的变化? [英] How to listen for changes to a MongoDB collection?
问题描述
我正在创建一种使用 MongoDB 作为数据存储的后台作业队列系统.我如何听"?在产生工作人员处理作业之前插入到 MongoDB 集合?
I'm creating a sort of background job queue system with MongoDB as the data store. How can I "listen" for inserts to a MongoDB collection before spawning workers to process the job?
我是否需要每隔几秒轮询一次以查看与上次相比是否有任何更改,或者我的脚本是否可以等待插入发生?
Do I need to poll every few seconds to see if there are any changes from last time, or is there a way my script can wait for inserts to occur?
这是我正在开发的 PHP 项目,但可以用 Ruby 或语言不可知论回答.
This is a PHP project that I am working on, but feel free to answer in Ruby or language agnostic.
推荐答案
MongoDB 有所谓的 上限集合
和 tailable cursors
允许 MongoDB 将数据推送到侦听器.
MongoDB has what is called capped collections
and tailable cursors
that allows MongoDB to push data to the listeners.
一个上限集合
本质上是一个固定大小并且只允许插入的集合.下面是创建一个的样子:
A capped collection
is essentially a collection that is a fixed size and only allows insertions. Here's what it would look like to create one:
db.createCollection("messages", { capped: true, size: 100000000 })
MongoDB Tailable 游标(Jonathan H. Wage 的原帖)
红宝石
coll = db.collection('my_collection')
cursor = Mongo::Cursor.new(coll, :tailable => true)
loop do
if doc = cursor.next_document
puts doc
else
sleep 1
end
end
PHP
$mongo = new Mongo();
$db = $mongo->selectDB('my_db')
$coll = $db->selectCollection('my_collection');
$cursor = $coll->find()->tailable(true);
while (true) {
if ($cursor->hasNext()) {
$doc = $cursor->getNext();
print_r($doc);
} else {
sleep(1);
}
}
Python(由 Robert Stewart 提供)
from pymongo import Connection
import time
db = Connection().my_db
coll = db.my_collection
cursor = coll.find(tailable=True)
while cursor.alive:
try:
doc = cursor.next()
print doc
except StopIteration:
time.sleep(1)
Perl(来自 Max)
use 5.010;
use strict;
use warnings;
use MongoDB;
my $db = MongoDB::Connection->new;
my $coll = $db->my_db->my_collection;
my $cursor = $coll->find->tailable(1);
for (;;)
{
if (defined(my $doc = $cursor->next))
{
say $doc;
}
else
{
sleep 1;
}
}
其他资源:
Ruby/Node.js 教程,带您完成创建一个应用程序来监听 MongoDB 上限集合中的插入.
使用可尾游标的 PHP、Ruby、Python 和 Perl 示例.
这篇关于如何监听 MongoDB 集合的变化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!