1

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!

userMod2
  • 8,312
  • 13
  • 63
  • 115

1 Answers1

3

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 }
elliotcm
  • 760
  • 4
  • 7
  • Thanks @elliotcm! Worked a treat - but I just want to understand exactly, so this blocks the main thread and in turn creates 2 new threads? Is there any consideration I need to take with this slowing/blocking other processes? = – userMod2 Aug 28 '18 at 23:48
  • Yes, that's right. It won't slow or block other processes, as all three threads in question will stay in this one process, but if your code is intended to do anything other than just this reading from RabbitMQ then you'll need to have some other kind of work loop to handle that. Most people don't, though, they have a completely separate process for things other than consumers. – elliotcm Aug 29 '18 at 15:30