Python Language How to consume messages from RabbitMQ


Start with importing the library.

from amqpstorm import Connection

When consuming messages, we first need to define a function to handle the incoming messages. This can be any callable function, and has to take a message object, or a message tuple (depending on the to_tuple parameter defined in start_consuming).

Besides processing the data from the incoming message, we will also have to Acknowledge or Reject the message. This is important, as we need to let RabbitMQ know that we properly received and processed the message.

def on_message(message):
    """This function is called on message received.

    :param message: Delivered message.
    print("Message:", message.body)

    # Acknowledge that we handled the message without any issues.

    # Reject the message.
    # message.reject()

    # Reject the message, and put it back in the queue.
    # message.reject(requeue=True)

Next we need to set up the connection to the RabbitMQ server.

connection = Connection('', 'guest', 'guest')

After that we need to set up a channel. Each connection can have multiple channels, and in general when performing multi-threaded tasks, it's recommended (but not required) to have one per thread.

channel =

Once we have our channel set up, we need to let RabbitMQ know that we want to start consuming messages. In this case we will use our previously defined on_message function to handle all our consumed messages.

The queue we will be listening to on the RabbitMQ server is going to be simple_queue, and we are also telling RabbitMQ that we will be acknowledging all incoming messages once we are done with them.

channel.basic.consume(callback=on_message, queue='simple_queue', no_ack=False)

Finally we need to start the IO loop to start processing messages delivered by the RabbitMQ server.