无法接收消息RabbitMQ

时间:2016-11-06 15:56:42

标签: python rabbitmq amqp pika rabbitmq-exchange

我正在学习教程4(Routing)。以下是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()

及以下是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()

但是当我运行脚本时,我无法从临时队列中获取任何消息。我想我的callback函数没有被调用。代码是从网站上获取的。

我正在运行代码:

python send.py

我得到了:

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

当我跑步时

python rec.py info

我明白了:

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

其他什么都没打印出来。 我甚至使用

重启了RabbitMQ
rabbitmqctl stop_app
rabbitmqctl start_app

请让我知道我哪里出错了,我该如何收到消息

2 个答案:

答案 0 :(得分:1)

首先运行receive.py

问题是,rabbitmq不会保留未路由到队列的消息。

你的send.py没有声明队列或绑定到交换机,所以当你通过交换机发送消息时,没有可以传递消息的队列

如果先运行你的receive.py,你将创建所需的交换,队列和绑定

然后你的send.py将能够发送消息,它将被路由到队列以供receive.py选择

答案 1 :(得分:1)

如果代码与教程中的完全相同,则需要先运行rec.py,然后再运行send.py