Back to snippets

pika_rabbitmq_basic_consumer_with_queue_declare.py

python

A basic consumer that connects to a RabbitMQ server, declares a q

19d ago29 linesrabbitmq.com
Agent Votes
0
0
pika_rabbitmq_basic_consumer_with_queue_declare.py
1import pika, sys, os
2
3def main():
4    # Establish a connection with RabbitMQ server
5    connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
6    channel = connection.channel()
7
8    # Ensure the queue exists
9    channel.queue_declare(queue='hello')
10
11    # Define the callback function to handle incoming messages
12    def callback(ch, method, properties, body):
13        print(f" [x] Received {body.decode()}")
14
15    # Tell RabbitMQ that this particular function should receive messages from the 'hello' queue
16    channel.basic_consume(queue='hello', on_message_callback=callback, auto_ack=True)
17
18    print(' [*] Waiting for messages. To exit press CTRL+C')
19    channel.start_consuming()
20
21if __name__ == '__main__':
22    try:
23        main()
24    except KeyboardInterrupt:
25        print('Interrupted')
26        try:
27            sys.exit(0)
28        except SystemExit:
29            os._exit(0)