Messaging in Python with RabbitMQ and Pika

17 Apr

I just started using RabbitMQ and Pika and sent a message – “hello world!” Cool, but so what. I threw an IF statement in my code to simulate reading the message and doing different tasks based on the content of the message. This is better, but still interested in doing more. How about sending binary data – files?

Sure!

I modified the simple tutorial producer and consumer to send a JPG. The producer opens a jpg image in binary mode RB and reads it to a variable. It then sends that variable to the queue.

The consumer knows to expect a jpg – but you could code all this in assuming it doesn’t know. It opens a blank file, gets the message and writes it to the file in binary mode – wb.

This is cool. Now we can send tasks – files to be operated on. And these tasks can be sent to multiple workers.

Here is the code:

SEND.PY

import pika
import logging
f=open(“image.jpg”,”rb”)
i=f.read()

logging.basicConfig()
connection = pika.BlockingConnection(pika.ConnectionParameters(host=’localhost’))
channel = connection.channel()

channel.queue_declare(queue=’hello’)

channel.basic_publish(exchange=”,routing_key=’hello’,body=i)
print ” [x] Sent ‘Hello World!'”
connection.close()

 

CONSUME.PY

import pika

f=open(“outputimage.jpg”,”wb”)

connection = pika.BlockingConnection(pika.ConnectionParameters(
host=’localhost’))
channel = connection.channel()

channel.queue_declare(queue=’hello’)

print ‘ [*] Waiting for messages. To exit press CTRL+C’

def callback(ch, method, properties, body):
f.write(body)
f.close()
channel.basic_consume(callback,
queue=’hello’,
no_ack=True)

channel.start_consuming()

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: