austen
austen

Reputation: 3314

How can I keep an AMQP connection open when using Ruby-Amqp?

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
  1. Is there a way to keep the AMQP connection open so I don't have to call 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

Answers (1)

big-circle
big-circle

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

Related Questions