歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Python 操作消息隊列

Python 操作消息隊列

日期:2017/3/1 9:12:46   编辑:Linux編程

閱讀目錄

  • 圖示
  • 插入消息隊列代碼
  • 讀取消息隊列數據

圖示

其中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。

Ubuntu 14.04安裝Python 3.3.5 http://www.linuxidc.com/Linux/2014-05/101481.htm

CentOS上源碼安裝Python3.4 http://www.linuxidc.com/Linux/2015-01/111870.htm

《Python核心編程 第二版》.(Wesley J. Chun ).[高清PDF中文版] http://www.linuxidc.com/Linux/2013-06/85425.htm

《Python開發技術詳解》.( 周偉,宗傑).[高清PDF掃描版+隨書視頻+代碼] http://www.linuxidc.com/Linux/2013-11/92693.htm

Python腳本獲取Linux系統信息 http://www.linuxidc.com/Linux/2013-08/88531.htm

在Ubuntu下用Python搭建桌面算法交易研究環境 http://www.linuxidc.com/Linux/2013-11/92534.htm

Python 語言的發展簡史 http://www.linuxidc.com/Linux/2014-09/107206.htm

Python 的詳細介紹:請點這裡
Python 的下載地址:請點這裡

Copyright © Linux教程網 All Rights Reserved