Working Ruby + Stomp example

I wasted too much time this morning getting Stomp for Ruby to work with ActiveMQ. The issue was that the example in the Stomp documentation did not work as is. It is missing a "join" call! Given the general weakness of the documentation perhaps I should have ignored the example sooner. Anyway, here are working consumer and producer examples. Firstly, ensure that ActiveMQ is configured for Stomp: Add to the "activemq.xml" configuration file, within the transportConnectors element, the following

<transportConnector name="stomp" uri="stomp://localhost:61613"/>

Save as "producer.rb" and run using "ruby producer.rb"

require 'rubygems'
require 'stomp'

now = DateTime.now.to_s
queue = "/queue/hellos"

puts "Producer for queue #{queue}"

client = Stomp::Client.new "system", "manager", "localhost", 61613, true

for i in 1..100
puts "producing #{i}"
client.send queue, "#{now} #{i} hello!", { :persistent => true }
sleep 1
end

client.close

Save as "consumer.rb" and run using "ruby consumer.rb"

require 'rubygems'
require 'stomp'

queue = "/queue/hellos"

puts "Consumer for queue #{queue}"

client = Stomp::Client.new "system", "manager", "localhost", 61613, true
client.subscribe queue, { :ack => :client } do | message |
puts "message=#{message.body}"
client.acknowledge message # tell the server the message was handled and to dispose of it
end
client.join # without this the above subscription is not activated.
client.close

1 comment:

Heylve 31 said...

First thanks for the examples :

client.send queue, "#{now} #{i} hello!", { :persistent => true }

client.publish works for me, it might have changed since 2009

Regards