圖示
其中P指producer,即生產者;C指consumer,即消費者。中間的紅色表示消息隊列,實例中表現為HELLO隊列。
往隊列里插入數據前,查看消息隊列
$sudo rabbitmqctl list_queues Listing queues ... celeryev.db53a5e0-1e6a-4f06-a9f7-2c104c4612fb 0 ...done.
插入消息隊列代碼
#in_queue.py
#coding=utf8 import pika connection = pika.BlockingConnection(pika.ConnectionParameters('localhost')) channel = connection.channel() #聲明隊列,如果消息發送到不存在的隊列,rabbitmq會自動清除這些消息 channel.queue_declare(queue='HELLO') for i in range(10): #exchange表示交換器,可以精確的制定消息應發到哪個隊列,route_key設置隊列的名稱,body表示發送的內容 channel.basic_publish(exchange='', routing_key='HELLO', body='Hello World!' + str(i)) print " [%d] Sent 'Hello World!'" % i #關閉連接 connection.close()
執行結果
$python in_queue.py [0] Sent 'Hello World!' [1] Sent 'Hello World!' [2] Sent 'Hello World!' [3] Sent 'Hello World!' [4] Sent 'Hello World!' [5] Sent 'Hello World!' [6] Sent 'Hello World!' [7] Sent 'Hello World!' [8] Sent 'Hello World!' [9] Sent 'Hello World!'
此時查看消息隊列
$sudo rabbitmqctl list_queues Listing queues ... HELLO 10 celeryev.db53a5e0-1e6a-4f06-a9f7-2c104c4612fb 0 ...done.
可以看到隊列HELLO里面有10條數據。
讀取消息隊列數據
#out_queue.py
#coding=utf8 import pika connection = pika.BlockingConnection(pika.ConnectionParameters('localhost')) channel = connection.channel() channel.queue_declare(queue='HELLO') def callback(ch, method, properties, body): print " [x] Received %r" % (body,) channel.basic_consume(callback, queue='HELLO', no_ack=True) print ' [*] Waiting for messages. To exit press CTRL+C' channel.start_consuming()
執行結果
$python out_queue.py [*] Waiting for messages. To exit press CTRL+C [x] Received 'Hello World!0' [x] Received 'Hello World!1' [x] Received 'Hello World!2' [x] Received 'Hello World!3' [x] Received 'Hello World!4' [x] Received 'Hello World!5' [x] Received 'Hello World!6' [x] Received 'Hello World!7' [x] Received 'Hello World!8' [x] Received 'Hello World!9'
此時查看消息隊列
$sudo rabbitmqctl list_queues Listing queues ... HELLO 0 celeryev.db53a5e0-1e6a-4f06-a9f7-2c104c4612fb 0 ...done.
可以看到隊列HELLO中的數據被讀走了,條數為0。
未完待續
http://www.01happy.com/ubuntu-rabbitmq-and-python-practice/