Search code examples
rubyrabbitmqbunny

Ruby Bunny - Consuming from Multiple Queues


I’ve just started using Ruby and am writing a piece to consume some messages from a RabbitMQ queue. I’m using Bunny to do so.

So I’ve created my queues and binded them to an exchange.

However I’m now unsure how I handle subscribing to them both and allowing the ruby app to continue running (want the messages to keep coming through i.e. not blocked or at least not for a long time) until I actually exit it with ctrl+c.

I’ve tried using :block => true however as I have 2 different queues I’m subscribing to, using this means it remains consuming from only one.

So this is how I’m consuming messages:

def consumer

    begin
      puts ' [*] Waiting for messages. To exit press CTRL+C'

      @oneQueue.subscribe(:manual_ack => true) do |delivery_info, properties, payload|
        puts('Got One Queue')
        puts "Received #{payload}, message properties are #{properties.inspect}"
      end

      @twoQueue.subscribe(:manual_ack => true) do |delivery_info, properties, payload|
        puts('Got Two Queue')
        puts "Received #{payload}, message properties are #{properties.inspect}"
      end

    rescue Interrupt => _
      #TODO - close connections here

      exit(0)
    end

end

Any help would be appreciated.

Thanks!


Solution

  • You can't use block: true when you have two subscriptions as only the first one will block; it'll never get to the second subscription.

    One thing you can do is set up both subscriptions without blocking (which will automatically spawn two threads to process messages), and then block your main thread with a wait loop (add just before your rescue):

    loop { sleep 5 }