1 模式介紹
生產者-消費者模式是最簡單的使用模式。
一個生產者P,給隊列發送消息,一個消費者C來取隊列的消息。
這里的隊列長度不限,生產者和消費者都不用考慮隊列的長度。
隊列的模型圖:
2 示例代碼
生產者

1 #!/usr/bin/env python 2 import pika 3 4 parameters = pika.ConnectionParameters('localhost') 5 connection = pika.BlockingConnection(parameters) 6 channel = connection.channel() 7 8 channel.queue_declare(queue='hello') 9 number = 0 10 while number < 5: 11 channel.basic_publish(exchange='', routing_key='hello', body="hello world: {}".format(number)) 12 print(" [x] Sent {}".format(number)) 13 number += 1 14 15 connection.close()
消費者

1 #!/usr/bin/env python 2 import pika 3 import datetime 4 5 parameters = pika.ConnectionParameters('localhost') 6 connection = pika.BlockingConnection(parameters) 7 channel = connection.channel() 8 9 channel.queue_declare(queue='hello') 10 11 12 def callback(ch, method, properties, body): # 定義一個回調函數,用來接收生產者發送的消息 13 print("{} [消費者] recv {}".format(datetime.datetime.now(), body)) 14 15 16 channel.basic_consume(callback, queue='hello', no_ack=True) 17 print('{} [消費者] waiting for msg .'.format(datetime.datetime.now())) 18 channel.start_consuming() # 開始循環取消息
執行輸出
生產者輸出:
[x] Sent 0 [x] Sent 1 [x] Sent 2 [x] Sent 3 [x] Sent 4
消費者輸出:
2018-07-06 16:10:05.308371 [消費者] waiting for msg . 2018-07-06 16:10:10.028588 [消費者] recv b'hello world: 0' 2018-07-06 16:10:10.028588 [消費者] recv b'hello world: 1' 2018-07-06 16:10:10.028588 [消費者] recv b'hello world: 2' 2018-07-06 16:10:10.028588 [消費者] recv b'hello world: 3' 2018-07-06 16:10:10.028588 [消費者] recv b'hello world: 4'
3 隊列信息
在web管理頁面上查看,點擊queues,可以看到:hello隊列