生产者代码:
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(
host='localhost'))
channel = connection.channel()
channel.queue_declare(queue='hello')
channel.basic_publish(exchange='',
routing_key='hello',
body='Hello World!')
print " [x] Sent 'Hello World!'"
connection.close()
消费者代码:
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(
host='localhost'))
channel = connection.channel()
channel.queue_declare(queue='hello')
print ' [*] Waiting for messages. To exit press CTRL+C'
def callback(ch, method, properties, body):
print " [x] Received %r" % (body,)
channel.basic_consume(callback,
queue='hello',
no_ack=True)
channel.start_consuming()
重点
1:producer和consumer都应该去声明一个队列,尽管只有producer才能真正有效的创建。
通过命令rabbitmqctl list_queues可查看当前有哪些queue
当前有new_priority,task_queue,new_task_queue,priority四个queue
**刚刚实验了,如果消费者不声明一个同样的queue居然不报错!以前一直以为会报错!**
2从架构图可以看出,Producer只能发送到exchange,它是不能直接发送到queue的。现在我们使用默认的exchange(名字是空字符)。这个默认的exchange允许我们发送给指定的queue。routing_key就是指定的queue名字。
3
channel.start_consuming()
此处为无线循环监听