MongoDB 有一个叫 Tailable Cursors的特性,它相似于tail -f 命令,你在一个Capped Collection上面执行查询操做,当操做完成后,你能够不关闭返回的数据Cursor,并持续地从中读出新加入的数据。node
这个特性能够用来干什么?我以为最直接的一个用途就是用做消息队列了,利用此特性加上MongoDB 自然的Replication 机制,作一个分布式的队列系统貌似不是什么难事。linux
Capped collections 就是固定大小的collection。 它有很高的性能以及队列过时的特性(过时按照插入的顺序)。 有点和 "RRD" 概念相似。git
What RRDtool does?github
RRDtool is the OpenSource industry standard, high performance data logging and graphing system for time series data.mongodb
**注:**Tailable Cursor在概念上,相似于Unix的tail命令的-f选项,即一种‘follow’模式。数据库
建立一个 Capped Collection编程
db.createCollection("mycoll", {capped:true, size:100000})缓存
和标准的collection不一样,你必需要显式的建立一个capped collection, 指定一个collection的大小,单位是字节。collection的数据存储空间值提早分配的。 要注意的是指定的存储大小包含了数据库的头信息。app
日志Logging.分布式
缓存Caching.
自动存档Auto Archiving.
使用tailable cursors
示例: oplog
注:
var filter = {}; // set MongoDB cursor options var cursorOptions = { tailable: true, awaitdata: true, numberOfRetries: -1 }; // create stream and listen var stream = coll.find(filter, cursorOptions).sort({$natural: -1}).stream(); // call the callback stream.on('data', function(document) { console.log(document); });
项目地址: https://github.com/scttnlsn/mubsub
mubsub基于node.js和mongoDB实现发布,订阅消息。
使用mongo的capped collections和tailable cursors,当插入指定文档时,通知订阅者。