在Python中利用 rabbitMQ實現生產與消費者模式的方法?很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細講解,有這方面需求的人可以來學習下,希望你能有所收獲。
(一)安裝一個消息中間件,如:rabbitMQ
(二)生產者
sendmq.py
import pika
import sys
import time
# 遠程rabbitmq服務的配置信息
username = 'admin' # 指定遠程rabbitmq的用戶名密碼
pwd = 'admin'
ip_addr = '10.1.7.7'
port_num = 5672
# 消息隊列服務的連接和隊列的創建
credentials = pika.PlainCredentials(username, pwd)
connection = pika.BlockingConnection(pika.ConnectionParameters(ip_addr, port_num, '/', credentials))
channel = connection.channel()
# 創建一個名為balance的隊列,對queue進行durable持久化設為True(持久化第一步)
channel.queue_declare(queue='balance', durable=True)
message_str = 'Hello World!'
for i in range(100000000):
# n RabbitMQ a message can never be sent directly to the queue, it always needs to go through an exchange.
channel.basic_publish(
exchange='',
routing_key='balance', # 寫明將消息發送給隊列balance
body=message_str, # 要發送的消息
properties=pika.BasicProperties(delivery_mode=2, ) # 設置消息持久化(持久化第二步),將要發送的消息的屬性標記為2,表示該消息要持久化
) # 向消息隊列發送一條消息
print(" [%s] Sent 'Hello World!'" % i)
# time.sleep(0.2)
connection.close() # 關閉消息隊列服務的連接運行sendmq.py文件,可以從以下方法查看隊列中的消息數量。
一是,rabbitmq的管理界面,如下圖所示:

二是,從服務器端命令查看
rabbitmqctl list_queues

(三)消費者
receivemq.py
import pika
import sys
import time
# 遠程rabbitmq服務的配置信息
username = 'admin' # 指定遠程rabbitmq的用戶名密碼
pwd = 'admin'
ip_addr = '10.1.7.7'
port_num = 5672
credentials = pika.PlainCredentials(username, pwd)
connection = pika.BlockingConnection(pika.ConnectionParameters(ip_addr, port_num, '/', credentials))
channel = connection.channel()
# 消費成功的回調函數
def callback(ch, method, properties, body):
print(" [%s] Received %r" % (time.time(), body))
# time.sleep(0.2)
# 開始依次消費balance隊列中的消息
channel.basic_consume(queue='balance', on_message_callback=callback, auto_ack=True)
print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming() # 啟動消費運行receivemq.py文件,可以從以下方法查看隊列中的消息數量。

或者
rabbitmqctl list_queues
延伸:
systemctl status rabbitmq-server.service # 狀態
systemctl restart rabbitmq-server.service # 重啟
看完上述內容是否對您有幫助呢?如果還想對相關知識有進一步的了解或閱讀更多相關文章,請關注億速云行業資訊頻道,感謝您對億速云的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。