RabbitMQ – Pika Notes

Pika Tutorial

Hoping that you already have RabbitMq server up and running on your local system, we have created this tutorial.

import pika
pika_cred = pika.PlainCredentials('guest', 'guest')
pika_conn_params = pika.ConnectionParameters('localhost', credentials=pika_cred)

pika_connection = pika.BlockingConnection(pika_conn_params)
channel = pika_connection.channel()

Declaring Queues

channel.queue_declare(queue='test-queue1')
channel.queue_declare(queue='test-queue2')

Declaring Exchanges

channel.exchange_declare(exchange='test-exchange', exchange_type='direct')

Declaring RoutingKey

channel.queue_bind(exchange='test-exchange', queue='test-queue1', routing_key='redpill')
channel.queue_bind(exchange='test-exchange', queue='test-queue2', routing_key='bluepill')

Testing

Sending
import pika
pika_cred = pika.PlainCredentials('guest', 'guest')
pika_conn_params = pika.ConnectionParameters('localhost', credentials=pika_cred)

pika_connection = pika.BlockingConnection(pika_conn_params)
channel = pika_connection.channel()

Lets send a hello world message to queue1.

channel.basic_publish(exchange='test-exchange', routing_key='redpill', body='Hello World!')
print(" [x] Sent 'Hello World!'")

Let’s also send a hello world message to queue2.

channel.basic_publish(exchange='test-exchange', routing_key='bluepill', body='Hello World2!')
print(" [x] Sent 'Hello World!'")

Let’s send a hello world message to exchange with a routing_key, we have not defined, to see what happens

channel.basic_publish(exchange='test-exchange', routing_key='greypill', body='Hello World3!')
print(" [x] Sent 'Hello World!'")

[x] Sent ‘Hello World!’

pika_connection.close()
Reading

Reading for test-queue1

pika_connection = pika.BlockingConnection(pika_conn_params)
channel = pika_connection.channel()
for each in channel.consume(queue='test-queue1', no_ack=True, inactivity_timeout=0):
if each:
print(each)
else:
break

Reading from test-queue2

pika_connection = pika.BlockingConnection(pika_conn_params)
channel = pika_connection.channel()
for each in channel.consume(queue='test-queue2', no_ack=True, inactivity_timeout=2):
if each:
print(each)
else:
break
Advertisements