Ruby and amqp gem

Hello all,

This is my first post in ruby forum and I am a beginner in ruby
scripting. I was developing a standalone script and my application is
communicating with workers through rabbitmq broker.Script will be
running periodically from cron. I was using amqp gem for the purpose
and its working like a charm. I was planning to rework on the script, on
the basis of a thought like , its not a good idea to start an amqp
conncetion and channel, each time publisher publishes message. So I was
planning to use the amqp connection and channel as an object and use it
throughout the messaging and stop it after publishing all messages.
Since the amqp gem is using event machine, its bit complicated to
understand the control flows. But I was able to make a working model and
I am sharing my code here. Please let me know, if there are any better
options or any mistake with my approach. I did amqp publisher as module
and here is my code for that

BEGIN

require ‘amqp’

module AmqpProducer
@exchange_name = “mail.exchange”
@auth = {

:host => “192.168.1.229”,
:user => “hans”,
:pass => “password”,
:vhost => “/”,
}

def self.start(login = @auth)
AMQP.start(login) do |connection, open_ok|
@connection = connection
AMQP::Channel.new(connection) do |channel|
@channel = channel
@exchange = @channel.direct(@exchange_name)
yield
end
end
end

def self.publish(message, options = {})
raise StandardError, " Must initialize AMQP " if @exchange == nil
@exchange.publish(message, options)
end

def self.stop
p “stopping”
@connection.close { EventMachine.stop }
end

end

END

Here is the basic controller code sample

BEGIN

require_relative ‘./producer_module.rb’

key = “mail.key”

message = “Hello MQ”

AmqpProducer.start do
p “publishing”

10.times do
p “sending”

AmqpProducer.publish(message, :routing_key => key)

end

AmqpProducer.stop

end

end

My main concern was that , since amqp gem is asynchronous, will it stop
the event machine before publishing all messages. But in this case I
think
@connection.close { EventMachine.stop } is gracefully stopping EM. But
not sure whether it will work in all cases. Please share your thoughts.

Thanks

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs