Reputation: 3314
I'm using RabbitMQ and ruby-amqp with Rails. When a message is received by a controller I perform the following:
def create
AMQP.start("amqp://localhost:5672") do |connection|
channel = AMQP::Channel.new(connection)
exchange = channel.direct("")
exchange.publish("some msg", :routing_key => "some key")
EventMachine.add_timer(2) do
exchange.delete
connection.close { EventMachine.stop }
end
end
end
start
every time a request comes in?I assume that opening a connection to Rabbit MQ is inefficient, however I haven't found a way to pass a block of code to a persistant connection.
Upvotes: 3
Views: 1358
Reputation: 547
If you just want to keep AMQP connection open, try to set a global variable to keep connection unique.
def start_em
EventMachine.run do
$connection = AMQP.connect(CONNECTION_SETTING) unless $connection
yield
end
end
def publish(message, options = {})
start_em {
channel = AMQP::Channel.new($connection)
exchange = channel.direct('')
exchange.publish(message, {:routing_key => 'rails01'}.merge(options))
EventMachine.add_timer(1) { exchange.delete }
}
end
And don't forget to delete channel after you pulish your message.
Upvotes: 1