python 操作訊息佇列

2021-09-09 04:25:47 字數 2922 閱讀 8689

其中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 10celeryev.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')

defcallback(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。

未完待續

python 操作訊息佇列

閱讀目錄 回到頂部 其中p指producer,即生產者 c指consumer,即消費者。中間的紅色表示訊息佇列,例項中表現為hello佇列。往佇列裡插入資料前,檢視訊息佇列 sudo rabbitmqctl list queues listing queues celeryev.db53a5e0 1...

Python操作rabbitmq訊息佇列持久化

訊息佇列持久化 python操作rabbit訊息佇列的持久化,如下 建立乙個名為balance的佇列,對queue進行durable持久化設為true 持久化第一步 channel.queue declare queue balance durable true 設定訊息持久化 持久化第二步 將要傳...

Python訊息佇列

訊息中介軟體 就是訊息佇列 非同步方式 不需要立馬得到結果,需要排隊 同步方式 需要實時獲得資料,堅決不能排隊 例子 多程序模組multiprocessing from multiprocessing import process from multiprocessing import queue ...