2016-11-06 170 views
0

我在接下来的教程4(Routing)。以下是send.py无法收到消息RabbitMQ

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 

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

回答

1

运行receive.py第一

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

您send.py不声明队列或结合的交流,所以当你通过Exchange发送邮件时,没有队列该消息可以传递,如果你运行

您收到首先的.py,你会创建所需的交换,队列和绑定

那么你send.py将能够发送邮件,它会被路由到队列中receive.py拿起

+1

殴打我了11秒:) – cantSleepNow

+0

好吧,得到那一个,所以这不是我们原始的发送和接收事情,谢谢队友! –

1

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