2

I'm using Rabbit MQ's Ruby client (Bunny).

I moved the hole Bunny config and initializing process in an initializer.

How can I access channels/queues opened on a Bunny connection from inside a controller or a lib?

I get 'true' when I call Bunny::Session#open? but I cannot seem to figure out how to access everything I need in that session.

Bogdan Popa
  • 1,099
  • 1
  • 16
  • 37

2 Answers2

4

Queues: If you give the queue a name, you can call .queue with the same name as much as you want, it will never create more than the one queue, but it will recreate the queue if it disappeared for any reason.

 handle_to_my_queue = $rabbit_channel.queue(queue_name)

Channels: If you create the channel with an id, then you can call create_channel and it will act like a "find or create".

For channels, you typically only need one, so I use a global variable (gasp, I know!).

config/initializers/rabbit.rb

$rabbit_connection = Bunny.new
$rabbit_connection.start
$rabbit_channel = $rabbit_connection.create_channel
Aaron Henderson
  • 1,840
  • 21
  • 20
3

As Aaron Henderson said, you just need a global variable which holds the connection session.

You can specify name while creating queues, and same name can be used to access it and the id parameter can be used to access the channel.

Initialize Bunny client with options like host, port and credentials:

$rmq_session = Bunny.new(
                          host: host,
                          port: port,
                          username: username,
                          password: password
                        )
$rmq_session.start

Create a channel with the bunny session.

sample_channel = $rmq_session.create_channel

The same channel can be accessed by the id parameter.

$rmq_session.channel(sample_channel.id)

Channels are identified by their ids which are integers. Bunny takes care of allocating and releasing them as channels are opened and closed. It is almost never necessary to specify channel ids explicitly. There is a limit on the maximum number of channels per connection, usually 65536. Note that allocating channels is very cheap on both client and server so having tens, hundreds or even thousands of channels is not a problem Read more about channel here.

Create a queue with the bunny session.

  sample_queue = sample_channel.queue('sample.queue')

You can access the above created queue by referring the queue name. This will not create new queue if already one exists.

  sample_queue = sample_channel.queue('sample.queue')
Community
  • 1
  • 1
Ashik Salman
  • 1,819
  • 11
  • 15