Working at Cloudant I use CouchDB on a daily basis. This evening for fun I decided to write some Ruby to take update notifications and push them into RabbitMQ. There are other examples of using the update notifications and Ruby in Couch such as the view updater out on the Couch wiki. It turned out super simple. There are a few AMQP libraries for Ruby, in this example I am going to use carrot. It’s based on the amqp library without all the eventmachine stuff. So here it goes:
#!/usr/bin/ruby
require ‘rubygems’
require ‘carrot’def main
queue = “couchdb”
run = true
couchq = Carrot.queue(:queue => queue)while run do
notifications = gets
if notifications == nil
run = false
else
couchq.publish(notifications)
endend
endmain
As you can tell we connect to a queue called “couchdb” on by default this is on localhost. Next we have a loop that continually runs and grabs updates from stdin. I then publish each notification to the queue and that’s that. To get the messages out of the queue I used irb and carrot.
[user@host ~]$ irb
irb(main):001:0> require ‘rubygems’
=> true
irb(main):002:0> require ‘carrot’
=> true
irb(main):003:0> couchq = Carrot.queue(:queue => “couchdb”)
=> #<Carrot::AMQP::Queue:0×7f8d2284b640 <snip>
irb(main):004:0> couchq.pop
=> “{\”type\”:\”updated\”,\”db\”:\”test1\”}\n”
So yeah, pretty simple stuff. Go ahead relax!
[EDIT 06/05/2009 2326 PST : Don't forget to add the entry to your local.ini]
[update_notification]
couch_amqp=/PATH/TO/couch_amqp.rb
Although Ruby is definitely quick out of the box, is there any particular reason you wouldn’t just plug this into couchdb via the erlang-amqp client?
Nah, no reason, it would likely be pretty easy to do with erlang and the amqp client. I just liked how simple it was to do with Ruby.
One advantage of doing this with the native erlang client is that you could actually plug it in to CouchDB at the server level rather than using the rather weak update notification that CouchDB currently supports (or the only-slightly-less-useless version of update notification that is on the way…)
Hey, you should port this code to use the new _changes API, in trunk, à la:
http://jchrisa.net/drl/_design/sofa/_show/post/Simple-Wins