in a main thread real time data from external sources Solution Queue up tasks and execute in background Queue up data and listen as needed Wednesday, April 11, 12
(channel, message) { console.log("I received message", message); console.log("on channel", channel); }); //subscribe to a channel client.subscribe("blarg"); //publish to a channel pub_client.publish("blarg", "sup bro?"); Messaging w/ Node Redis does it nicely messaging should be this easy with mongo + nodejs Wednesday, April 11, 12
message backlog can do: indexes, query, map reduce - nested objects and atomic updates • Avoid running another server, if it makes sense • You get durability and failover for free Wednesday, April 11, 12
on the queue Consumer - remove and return highest priority item from the queue db.queue.insert( { message:”iceberg right ahead”, sender:”some guy”, priority: 1000 } ); db.queue.findAndModify({sort:{priority:-1}, remove:true}) Wednesday, April 11, 12
an asynchronous external API •Failover - should be reliable and automatic •Message consumption - customizable using EventEmitter interface (like redis client) strategy #1 - Atomic Queue (findAndModify) Wednesday, April 11, 12
500, remove : true}); pq.addQuery("announcements", {“destination”:”announcements”}); pq.on("message", function(doc, filterId){ console.log("received from ", filterId, doc); }); pq.start(); PollQueue Class clean interface to message queue (EventEmitter) hide all the nasty details optional - we could also update Wednesday, April 11, 12
. . } inherits(PollQueue, EventEmitter); ... this.emit(“ready”, ...); this.emit(“message”, ...); Implementation inherit from EventEmitter: now we can emit() incoming data from mongo Wednesday, April 11, 12
works on capped collections db.createCollection({“queue”, {capped:true, size:10000000, autoIndexId:true} important if you’re using replica set capped collection - works like a circular queue Wednesday, April 11, 12
- need to poll for first msg • On failover, need to re-initialize cursors • if collection is non-empty, need to find latest element to start from strategy #2 - topic Publish/Subscribe (tailable cursors) Wednesday, April 11, 12
• Message producers/consumers no longer need to touch DB • Consistent abstractions for message ACK/NACK • Supports transactions (batch SEND with BEGIN/COMMIT/ABORT) Wednesday, April 11, 12