rabbitmq学习笔记----伟大的"hello world"
- 上节回顾
上篇所学:RabbitMQ实现了AMQP定义的消息队列。它实现的功能”非常简单“:从Producer接收数据然后传递到Consumer。它能保证多并发,数据安全传递,可扩展。
和任何的Hello world一样,它们都不复杂。我们将会设计两个程序,一个发送Hello world,另一个接收这个数据并且打印到屏幕
- 本节内容设计图

- send messages方:
from amqplib import client_0_8 as amqp import sys ##创建con和chanel con = amqp.Connection(host="192.168.1.188:32769", userid="guest", password="guest", virtual_host="/") chan = con.channel() ####创建queue chan.queue_declare(queue="hello") ####创建消息 massage = ' '.join(sys.argv[1:]) msg = amqp.Message(massage) ###发送message chan.basic_publish(msg,exchange='',routing_key="hello") ####关闭 chan.close() con.close()
从上一章的软件架构图可以看出,Producer只能发送到exchange,它是不能直接发送到queue的。现在我们使用默认的exchange(名字是空字符)。这个默认的exchange允许我们发送给指定的queue。routing_key就是指定的queue名字。
运行prodcut.py

list一下queue

- receive messages方:
from amqplib import client_0_8 as amqp import time ##创建con和chanel con = amqp.Connection(host="192.168.1.188:32769", userid="guest", password="guest", virtual_host="/") chan = con.channel() ####创建queue chan.queue_declare(queue="hello") ######定义回调函数 def recv_callback(msg): print('Received: ' + msg.body + ' from channel #' + str(msg.channel.channel_id)) ######开始消费、consume chan.basic_consume(queue="hello",callback=recv_callback,consumer_tag="testtag") #####开始监听 while True: chan.wait() ######取消消费 chan.basic_cancle("testtag") ###关闭连接 chan.close() con.close()
comsum.py 将从queue中获取Message并且打印到屏幕。

list一下queue

文章转载来源于:http://blog.csdn.net/anzhsoft/article/details/19570187

浙公网安备 33010602011771号