其中P指producer,即生產者;C指consumer,即消費者。中間的紅色表示消息隊列,實例中表現爲HELLO隊列。python
往隊列裏插入數據前,查看消息隊列ubuntu
$sudo rabbitmqctl list_queues Listing queues ... celeryev.db53a5e0-1e6a-4f06-a9f7-2c104c4612fb 0 ...done.
#in_queue.pyapp
#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()
執行結果spa
$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!'
此時查看消息隊列code
$sudo rabbitmqctl list_queues Listing queues ... HELLO 10 celeryev.db53a5e0-1e6a-4f06-a9f7-2c104c4612fb 0 ...done.
能夠看到隊列HELLO裏面有10條數據。blog
#out_queue.pyrabbitmq
#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。it
未完待續
http://www.01happy.com/ubuntu-rabbitmq-and-python-practice/