-
-
Save rjungemann/418422 to your computer and use it in GitHub Desktop.
Simplistic Ruby message queue
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Very efficient message queue backed by redis, using msgpack for serialization. | |
| require 'rubygems' | |
| require 'redis' | |
| require 'digest/md5' | |
| require 'msgpack' | |
| $redis = Redis.new | |
| class Queue | |
| def initialize(name) | |
| @name = name | |
| end | |
| def push(object) | |
| hash = Digest::MD5.hexdigest(object.to_s) | |
| $redis.set("msg:#{hash}", MessagePack.pack(object)) | |
| $redis.rpush("queue:#{@name}", hash) | |
| end | |
| def subscribe | |
| loop do | |
| hash = $redis.blpop("queue:#{@name}", 0)[1] | |
| object = $redis.get("msg:#{hash}") | |
| begin | |
| yield MessagePack.unpack(object) | |
| $redis.del("msg:#{hash}") | |
| rescue | |
| $redis.lpush("queue:#{@name}", hash) | |
| end | |
| end | |
| end | |
| end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment