begin
b = (Thread.current[:bunny] ||= Bunny.new(:host => AMQ_HOST))
b.start unless b.status == :connected
q = (Thread.current[queue] ||= b.queue(QUEUE_NAME))
q.publish(message)
rescue Exception => e
Thread.current[:bunny] = nil # Force a reconnection
retry if (retries -= 1) >= 0
end
The first time this section of code runs it opens the connection and stores it for reuse. The thread-local variables prevent multiple threads from running into each other. This approach is working fine (but I'm open to suggestions!).