0

I am following tutorial 4 (Routing). Following is the code for send.py

import pika
import sys

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

channel.exchange_declare(exchange='direct_logs',
                         type='direct')

severity = sys.argv[1] if len(sys.argv) > 1 else 'info'
message = ' '.join(sys.argv[2:]) or 'Hello World!'


channel.basic_publish(exchange='direct_logs',
                      routing_key=severity,
                      body=message)
print(" [x] Sent %r:%r" % (severity, message))
connection.close()

and below is the code for receive.py

import pika
import sys

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

channel.exchange_declare(exchange='direct_logs',
                         type='direct')

result = channel.queue_declare(exclusive=True)
queue_name = result.method.queue

severities = sys.argv[1:]
if not severities:
    sys.stderr.write("Usage: %s [info] [warning] [error]\n" % sys.argv[0])
    sys.exit(1)

for severity in severities:
    channel.queue_bind(exchange='direct_logs',
                       queue=queue_name,
                       routing_key=severity)

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

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

channel.basic_consume(callback,queue=queue_name,no_ack=True)
channel.start_consuming()

But when I am running the scripts I'm unable to fetch any message from the temporary queue. I guess my callback function is not being called. The codes are taken as it is from the site.

I am running the codes as:

python send.py

for which I'm getting:

 [x] Sent 'info':'Hello World!'

And when I run

python rec.py info

I get:

 [*] Waiting for logs. To exit press CTRL+C

And else nothing is printed. I have even restarted RabbitMQ using

rabbitmqctl stop_app
rabbitmqctl start_app

Please let me know where am I going wrong and how can I get message

Paul Schimmer
  • 161
  • 3
  • 22

2 Answers2

1

run the receive.py first

the problem is, rabbitmq will not hold messages that are not routed to queues.

your send.py does not declare a queue or a binding to the exchange, so when you send a message through the exchange, there is no queue to which the message can be delivered

if you run your receive.py first, you'll create the needed exchange, queue and binding

then your send.py will be able to send the messages and it will be routed to the queue for the receive.py to pick up

Derick Bailey
  • 72,004
  • 22
  • 206
  • 219
1

If the code is exactly like in the tutorial, you need to run rec.py first and then send.py

cantSleepNow
  • 9,691
  • 5
  • 31
  • 42