How to connect to ActiveMQ in Ruby

There are some Ruby gems to do the job, e.g.

activemessaging

and

https://github.com/stompgem/stomp

Here is the example of using stomp:

Publisher’s code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
require 'rubygems'
require 'stomp'
class StompPublisherTest
def initialize
end
def run
user = ""
pass = ""
host = "YOUR HOST NAME"
port = '61613'
publish_to = '/queue/test_messages'
client = Stomp::Client.new(user, pass, host, port)
message = "test_messages #{ARGV[0]}"
for i in (1..5)
puts 'Sending message'
client.publish(publish_to, "#{i}: #{message}", {:persistent => true})
puts "(#{Time.now})Message sent: #{i}"
sleep 0.2
end
end
end
spt = StompPublisherTest.new
spt.run

And here is the consumer’s code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
require 'rubygems'
require 'stomp'
class StompConsumerTest
def initialize
end
def run
user = ""
pass = ""
host = "YOUR HOST NAME"
port = '61613'
subscribe_to = '/queue/test_messages'
client = Stomp::Client.new(user, pass, host, port)
puts 'Subscribing ' + subscribe_to
client.subscribe(subscribe_to, {:ack => "client", "activemq.prefetchSize" => 1, "activemq.exclusive" => true }) do |msg|
File.open("messageclient.log", "a") do |f|
puts '----------received message-----------'
puts msg.body
f.write(msg.body)
f.write("\n----------------\n")
end
client.acknowledge(msg)
end
loop do
sleep(1)
print "."
end
end
end
st = StompConsumerTest.new
st.run
Share