RabbitMQ Python Test/Demo Programs

Introduction

These step assume the test programs are running on the Ubuntu server. I am currently using Ubuntu 17.04.

Base on: "Hello World!" Tutorial

Step 1. Install PIKA

sudo apt-get install python-pika

Step 2. Create a Work Directory

mkdir rmq-python
cd rmq-python

Step 3. Create send.py and receive.py

touch send.py
chmod a+x send.py

touch receive.py
chmod a+x receive.py

Cut and paste the code shown below.

Step 4. Verify RabbitMQ is Running

sudo rabbitmqctl list_queues
sudo rabbitmqctl list_exchanges
sudo rabbitmqctl list_bindings

Step 5. Run the Test Programs

You can run send.py and receive.py seperately or at the same time.

send.py

#!/usr/bin/env python
import pika

connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))

channel = connection.channel()

channel.queue_declare(queue='hello')

channel.basic_publish(exchange='',
                      routing_key='hello',
                      body='Hello World!')

print(' [x] Sent Hello World!')

while True:
    message = raw_input('Enter message: ')

    message = message.strip()

    if not message:
        break

    print(' [x] Send ' + message)

    channel.basic_publish(exchange='',
                          routing_key='hello',
                          body=message)    

connection.close()

receive.py

#!/usr/bin/env python
import pika

connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))

channel = connection.channel()

channel.queue_declare(queue='hello')

def callback(ch, method, properties, body):
    print(" [x] Received %r" % body)

channel.basic_consume(callback,
                      queue='hello',
                      no_ack=True)

print(' [*] Waiting for messages. To exit press CTRL+C')

channel.start_consuming()