CentOS 8
Sponsored Link

RabbitMQ : Use on Ruby
2020/04/17
 
This is an example to use RabbitMQ on Ruby.
[1] Install AMQP client library.
[cent@dlp ~]$
gem install bunny

Fetching amq-protocol-2.3.1.gem
Fetching bunny-2.15.0.gem
Successfully installed amq-protocol-2.3.1
Successfully installed bunny-2.15.0
Parsing documentation for amq-protocol-2.3.1
Installing ri documentation for amq-protocol-2.3.1
Parsing documentation for bunny-2.15.0
Installing ri documentation for bunny-2.15.0
Done installing documentation for amq-protocol, bunny after 1 seconds
2 gems installed
[2] This is an example of sending message on Ruby.
For example, connect with RabbitMQ on [localhost] with a user [serverworld], virtualhost [my_vhost].
[cent@dlp ~]$
vi send_msg.rb
require "bunny"

connection = Bunny.new(
    :hostname => "127.0.0.1",
    :port => 5672,
    :vhost => "/my_vhost",
    :user => "serverworld",
    :pass => "password",
)
connection.start

channel = connection.create_channel

q = channel.queue("Hello_World")
channel.default_exchange.publish("Hello RabbitMQ World!", :routing_key => q.name)
puts " [x] Sent 'Hello RabbitMQ World!'"

connection.close

[cent@dlp ~]$
ruby send_msg.rb

 [x] Sent 'Hello RabbitMQ World!'
[3] This is an example of receiving message on Ruby.
[cent@node01 ~]$
vi receive_msg.rb
require "bunny"

Signal.trap(:INT){
    puts "Exited from receiving queues."
    exit(0)
}

connection = Bunny.new(
    :hostname => "10.0.0.30",
    :port => 5672,
    :vhost => "/my_vhost",
    :user => "serverworld",
    :pass => "password",
)
connection.start

channel = connection.create_channel
q = channel.queue("Hello_World")

puts " [*] Waiting for messages in #{q.name}. To exit press CTRL+C"
q.subscribe(:block => true) do |delivery_info, properties, body|
    puts " [x] Received #{body}"

    delivery_info.consumer.cancel
end

[cent@node01 ~]$
ruby receive_msg.rb

 [*] Waiting for messages in Hello_World. To exit press CTRL+C
 [x] Received Hello RabbitMQ World!
Matched Content