我正在创建一种后台作业(job)队列系统,使用MongoDB作为数据存储.在生成处理作业(job)的工作人员之前,如何"侦听"MongoDB集合的插入?
我是否需要每隔几秒钟进行一次轮询,以查看与上次相比是否有任何更改,或者我的脚本是否有办法等待插入发生?
这是我正在做的一个PHP项目,但请随意用Ruby或不可知语言回答.
我正在创建一种后台作业(job)队列系统,使用MongoDB作为数据存储.在生成处理作业(job)的工作人员之前,如何"侦听"MongoDB集合的插入?
我是否需要每隔几秒钟进行一次轮询,以查看与上次相比是否有任何更改,或者我的脚本是否有办法等待插入发生?
这是我正在做的一个PHP项目,但请随意用Ruby或不可知语言回答.
MongoDB有所谓的capped collections
和tailable cursors
,允许MongoDB将数据推送到监听器.
capped collection
基本上是一个固定大小的集合,只允许插入.下面是创建一个的样子:
db.createCollection("messages", { capped: true, size: 100000000 })
Ruby
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;
}
}
An article talking about tailable cursors in more detail.
PHP, Ruby, Python, and Perl examples of using tailable cursors.