JMS with JRuby and ActiveMQ
One of the most interesting (and powerful) features of JRuby is the ability to access and manipulate Java classes and libraries. The code below creates, configures and starts an instance of an ActiveMQ Broker that accepts connections based on the Stomp protocol.
[ruby]
require “java”
require “apache-activemq-4.1.1.jar”
include_class “org.apache.activemq.broker.BrokerService”
broker = BrokerService.new
broker.add_connector(”stomp://localhost:61613″)
broker.start
[/ruby]
Supposing this code has been saved in a file named broker.rb, and given a working JRuby installation, we can start the Broker by invoking jruby broker.rb.
The apache-activemq-4.1.1.jar archive must be in the same location as the broker.rb script, in order for it to be successfully loaded. Alternatively it can be placed in any of the locations described in the Require and Load behavior page on the JRuby Wiki.
Ruby supports Stomp via the Stomp library which can be installed as a gem (gem install stomp). Using Stomp we can create Listeners that can subscribe to Topics on our queue.
[ruby]
require “rubygems”
require “stomp”
conn = Stomp::Connection.open(”", “”, “localhost”, 61613, false)
conn.subscribe(”/topic/testing”, {:ack => :auto})
loop do
p conn.receive.body
end
[/ruby]
Similarly, a Publisher would look something along the lines of:
[ruby]
require “rubygems”
require “stomp”
conn = Stomp::Connection.open(”", “”, “localhost”, 61613, false)
conn.send(”/topic/testing”, “Rock!!!”, {:persistent => false})
[/ruby]
Given the Broker is running, we can start the Listener, which will subscribe to the specified topic and print out any incoming messages. This can be demonstrated by running the Publisher that will post a text message to /topic/testing.

October 1st, 2007 at 8:23 am
[...] Nutrun » Blog Archive » JMS with JRuby and ActiveMQ (tags: Ruby programming messaging jms jruby activemq stomp) [...]