Oct 01 2007

Embedding Queueue

As of version 0.0.3, Queueue can be embedded in Ruby code through its QueueService interface. In this mode, Queueue could be used as a simple alternative for instrumenting message driven Ruby code.

require "rubygems"
require "queueue"

QUEUE_NAME = "queue"
SERVICE = Queueue::QueueService.new

SERVICE.create_queue QUEUE_NAME
SERVICE.set_visibility_timeout QUEUE_NAME, 5

listener = Thread.new do
  loop do
    messages = SERVICE.receive_message QUEUE_NAME
    messages.each do |msg|
      p msg.body
      SERVICE.delete_message QUEUE_NAME, msg.message_id
    end
  end
end

talker = Thread.new do
  %w(We've been dancing with Mr Brownstone).each do |msg|
    SERVICE.send_message QUEUE_NAME, msg
    sleep 2
  end
  p "Done. Exiting running threads"
  Thread.list.each { |t| t.exit! }
end

talker.join
listener.join

Another interesting scenario can involve QueueService combined with DRb as a means to instrumenting distributed Ruby processes.

An instance of QueueService wrapped inside a DRb server:

require "drb"
require "rubygems"
require "queueue"

DRb.start_service "druby://0.0.0.0:7777", Queueue::QueueService.new
DRb.thread.join

And DRb clients posting and consuming messages:

require "drb"
require "rubygems"
require "queueue"

service = DRbObject.new nil, 'druby://0.0.0.0:7777'
service.create_queue 'q'
service.send_message 'q', "We've been dancing with Mr Brownstone"
messages = service.receive_message 'q'
messages.first.body # => "We've been dancing with Mr Brownstone"