【问题标题】:Not able to recieve the messages RabbitMQ无法接收消息 RabbitMQ
【发布时间】:2017-03-19 23:30:27
【问题描述】:

我正在关注教程 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

请让我知道我哪里出错了,我怎样才能得到消息

【问题讨论】:

    标签: python rabbitmq amqp pika rabbitmq-exchange


    【解决方案1】:

    先运行receive.py

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

    您的 send.py 没有声明队列或与交换的绑定,因此当您通过交换发送消息时,没有可以将消息传递到的队列

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

    然后您的 send.py 将能够发送消息,并将其路由到队列以供 receive.py 接收

    【讨论】:

    • 比我快 11 秒 :)
    • 好的,这不是我们原始的发送和接收的东西,谢谢伙计!
    【解决方案2】:

    如果代码和教程中的一模一样,需要先运行rec.py再运行send.py

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多