Python操作rabbitMQ的示例代碼
引入
RabbitMQ 是一個(gè)由 Erlang 語(yǔ)言開發(fā)的 AMQP 的開源實(shí)現(xiàn)。
rabbitMQ是一款基于AMQP協(xié)議的消息中間件,它能夠在應(yīng)用之間提供可靠的消息傳輸。在易用性,擴(kuò)展性,高可用性上表現(xiàn)優(yōu)秀。使用消息中間件利于應(yīng)用之間的解耦,生產(chǎn)者(客戶端)無需知道消費(fèi)者(服務(wù)端)的存在。而且兩端可以使用不同的語(yǔ)言編寫,大大提供了靈活性。
安裝
# 安裝配置epel源 rpm -ivh http://dl.fedoraproject.org/pub/epel/6/i386/epel-release-6-8.noarch.rpm # 安裝erlang yum -y install erlang # 安裝RabbitMQ yum -y install rabbitmq-server # 啟動(dòng)/停止 service rabbitmq-server start/stop
rabbitMQ工作模型
簡(jiǎn)單模式
生產(chǎn)者
import pika connection = pika.BlockingConnection(pika.ConnectionParameters( host='localhost')) channel = connection.channel() channel.queue_declare(queue='hello') channel.basic_publish(exchange='', routing_key='hello', body='Hello World!') print(" [x] Sent 'Hello World!'") connection.close()
消費(fèi)者
connection = pika.BlockingConnection(pika.ConnectionParameters(host='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()
相關(guān)參數(shù)
1,no-ack = False
如果消費(fèi)者遇到情況(its channel is closed, connection is closed, or TCP connection is lost)掛掉了,那么,RabbitMQ會(huì)重新將該任務(wù)添加到隊(duì)列中。
- 回調(diào)函數(shù)中的 ch.basic_ack(delivery_tag=method.delivery_tag)
- basic_comsume中的no_ack=False
接收消息端應(yīng)該這么寫:
import pika connection = pika.BlockingConnection(pika.ConnectionParameters( host='10.211.55.4')) channel = connection.channel() channel.queue_declare(queue='hello') def callback(ch, method, properties, body): print(" [x] Received %r" % body) import time time.sleep(10) print 'ok' ch.basic_ack(delivery_tag = method.delivery_tag) channel.basic_consume(callback, queue='hello', no_ack=False) print(' [*] Waiting for messages. To exit press CTRL+C') channel.start_consuming()
2,durable :消息不丟失
生產(chǎn)者
import pika connection = pika.BlockingConnection(pika.ConnectionParameters(host='10.211.55.4')) channel = connection.channel() # make message persistent channel.queue_declare(queue='hello', durable=True) channel.basic_publish(exchange='', routing_key='hello', body='Hello World!', properties=pika.BasicProperties( delivery_mode=2, # make message persistent )) print(" [x] Sent 'Hello World!'") connection.close()
3,消息獲取順序
默認(rèn)消息隊(duì)列里的數(shù)據(jù)是按照順序被消費(fèi)者拿走,例如:消費(fèi)者1 去隊(duì)列中獲取 奇數(shù) 序列的任務(wù),消費(fèi)者1去隊(duì)列中獲取 偶數(shù) 序列的任務(wù)。
channel.basic_qos(prefetch_count=1) 表示誰(shuí)來誰(shuí)取,不再按照奇偶數(shù)排列
import pika connection = pika.BlockingConnection(pika.ConnectionParameters(host='10.211.55.4')) channel = connection.channel() # make message persistent channel.queue_declare(queue='hello') def callback(ch, method, properties, body): print(" [x] Received %r" % body) import time time.sleep(10) print 'ok' ch.basic_ack(delivery_tag = method.delivery_tag) channel.basic_qos(prefetch_count=1) channel.basic_consume(callback, queue='hello', no_ack=False) print(' [*] Waiting for messages. To exit press CTRL+C') channel.start_consuming()
exchange模型
1,發(fā)布訂閱
發(fā)布訂閱和簡(jiǎn)單的消息隊(duì)列區(qū)別在于,發(fā)布訂閱會(huì)將消息發(fā)送給所有的訂閱者,而消息隊(duì)列中的數(shù)據(jù)被消費(fèi)一次便消失。所以,RabbitMQ實(shí)現(xiàn)發(fā)布和訂閱時(shí),會(huì)為每一個(gè)訂閱者創(chuàng)建一個(gè)隊(duì)列,而發(fā)布者發(fā)布消息時(shí),會(huì)將消息放置在所有相關(guān)隊(duì)列中。
exchange type = fanout
生產(chǎn)者
import pika import sys connection = pika.BlockingConnection(pika.ConnectionParameters( host='localhost')) channel = connection.channel() channel.exchange_declare(exchange='logs', type='fanout') message = ' '.join(sys.argv[1:]) or "info: Hello World!" channel.basic_publish(exchange='logs', routing_key='', body=message) print(" [x] Sent %r" % message) connection.close()
消費(fèi)者
import pika connection = pika.BlockingConnection(pika.ConnectionParameters( host='localhost')) channel = connection.channel() channel.exchange_declare(exchange='logs', type='fanout') result = channel.queue_declare(exclusive=True) queue_name = result.method.queue channel.queue_bind(exchange='logs', queue=queue_name) print(' [*] Waiting for logs. To exit press CTRL+C') def callback(ch, method, properties, body): print(" [x] %r" % body) channel.basic_consume(callback, queue=queue_name, no_ack=True) channel.start_consuming()
2,關(guān)鍵字發(fā)送
之前事例,發(fā)送消息時(shí)明確指定某個(gè)隊(duì)列并向其中發(fā)送消息,RabbitMQ還支持根據(jù)關(guān)鍵字發(fā)送,即:隊(duì)列綁定關(guān)鍵字,發(fā)送者將數(shù)據(jù)根據(jù)關(guān)鍵字發(fā)送到消息exchange,exchange根據(jù) 關(guān)鍵字 判定應(yīng)該將數(shù)據(jù)發(fā)送至指定隊(duì)列。
exchange type = direct
import pika import sys connection = pika.BlockingConnection(pika.ConnectionParameters( host='localhost')) channel = connection.channel() channel.exchange_declare(exchange='direct_logs', type='direct') result = channel.queue_declare(exclusive=True) queue_name = result.method.queue severities = sys.argv[1:] if not severities: sys.stderr.write("Usage: %s [info] [warning] [error]\n" % sys.argv[0]) sys.exit(1) for severity in severities: channel.queue_bind(exchange='direct_logs', queue=queue_name, routing_key=severity) print(' [*] Waiting for logs. To exit press CTRL+C') def callback(ch, method, properties, body): print(" [x] %r:%r" % (method.routing_key, body)) channel.basic_consume(callback, queue=queue_name, no_ack=True) channel.start_consuming()
3,模糊匹配
exchange type = topic
發(fā)送者路由值 隊(duì)列中
old.boy.python old.* -- 不匹配
old.boy.python old.# -- 匹配
在topic類型下,可以讓隊(duì)列綁定幾個(gè)模糊的關(guān)鍵字,之后發(fā)送者將數(shù)據(jù)發(fā)送到exchange,exchange將傳入”路由值“和 ”關(guān)鍵字“進(jìn)行匹配,匹配成功,則將數(shù)據(jù)發(fā)送到指定隊(duì)列。
- # 表示可以匹配 0 個(gè) 或 多個(gè) 單詞
- * 表示只能匹配 一個(gè) 單詞
import pika import sys connection = pika.BlockingConnection(pika.ConnectionParameters( host='localhost')) channel = connection.channel() channel.exchange_declare(exchange='topic_logs', type='topic') result = channel.queue_declare(exclusive=True) queue_name = result.method.queue binding_keys = sys.argv[1:] if not binding_keys: sys.stderr.write("Usage: %s [binding_key]...\n" % sys.argv[0]) sys.exit(1) for binding_key in binding_keys: channel.queue_bind(exchange='topic_logs', queue=queue_name, routing_key=binding_key) print(' [*] Waiting for logs. To exit press CTRL+C') def callback(ch, method, properties, body): print(" [x] %r:%r" % (method.routing_key, body)) channel.basic_consume(callback, queue=queue_name, no_ack=True) channel.start_consuming()
基于rabbitMQ的RPC
Callback queue 回調(diào)隊(duì)列
一個(gè)客戶端向服務(wù)器發(fā)送請(qǐng)求,服務(wù)器端處理請(qǐng)求后,將其處理結(jié)果保存在一個(gè)存儲(chǔ)體中。而客戶端為了獲得處理結(jié)果,那么客戶在向服務(wù)器發(fā)送請(qǐng)求時(shí),同時(shí)發(fā)送一個(gè)回調(diào)隊(duì)列地址 reply_to 。
Correlation id 關(guān)聯(lián)標(biāo)識(shí)
一個(gè)客戶端可能會(huì)發(fā)送多個(gè)請(qǐng)求給服務(wù)器,當(dāng)服務(wù)器處理完后,客戶端無法辨別在回調(diào)隊(duì)列中的響應(yīng)具體和那個(gè)請(qǐng)求時(shí)對(duì)應(yīng)的。為了處理這種情況,客戶端在發(fā)送每個(gè)請(qǐng)求時(shí),同時(shí)會(huì)附帶一個(gè)獨(dú)有 correlation_id 屬性,這樣客戶端在回調(diào)隊(duì)列中根據(jù) correlation_id 字段的值就可以分辨此響應(yīng)屬于哪個(gè)請(qǐng)求。
客戶端發(fā)送請(qǐng)求:
某個(gè)應(yīng)用將請(qǐng)求信息交給客戶端,然后客戶端發(fā)送RPC請(qǐng)求,在發(fā)送RPC請(qǐng)求到RPC請(qǐng)求隊(duì)列時(shí),客戶端至少發(fā)送帶有reply_to以及correlation_id兩個(gè)屬性的信息
服務(wù)端工作流:
等待接受客戶端發(fā)來RPC請(qǐng)求,當(dāng)請(qǐng)求出現(xiàn)的時(shí)候,服務(wù)器從RPC請(qǐng)求隊(duì)列中取出請(qǐng)求,然后處理后,將響應(yīng)發(fā)送到reply_to指定的回調(diào)隊(duì)列中
客戶端接受處理結(jié)果:
客戶端等待回調(diào)隊(duì)列中出現(xiàn)響應(yīng),當(dāng)響應(yīng)出現(xiàn)時(shí),它會(huì)根據(jù)響應(yīng)中correlation_id字段的值,將其返回給對(duì)應(yīng)的應(yīng)用
服務(wù)者
import pika # 建立連接,服務(wù)器地址為localhost,可指定ip地址 connection = pika.BlockingConnection(pika.ConnectionParameters( host='localhost')) # 建立會(huì)話 channel = connection.channel() # 聲明RPC請(qǐng)求隊(duì)列 channel.queue_declare(queue='rpc_queue') # 數(shù)據(jù)處理方法 def fib(n): if n == 0: return 0 elif n == 1: return 1 else: return fib(n-1) + fib(n-2) # 對(duì)RPC請(qǐng)求隊(duì)列中的請(qǐng)求進(jìn)行處理 def on_request(ch, method, props, body): n = int(body) print(" [.] fib(%s)" % n) # 調(diào)用數(shù)據(jù)處理方法 response = fib(n) # 將處理結(jié)果(響應(yīng))發(fā)送到回調(diào)隊(duì)列 ch.basic_publish(exchange='', routing_key=props.reply_to, properties=pika.BasicProperties(correlation_id = \ props.correlation_id), body=str(response)) ch.basic_ack(delivery_tag = method.delivery_tag) # 負(fù)載均衡,同一時(shí)刻發(fā)送給該服務(wù)器的請(qǐng)求不超過一個(gè) channel.basic_qos(prefetch_count=1) channel.basic_consume(on_request, queue='rpc_queue') print(" [x] Awaiting RPC requests") channel.start_consuming()
客戶端
import pika import uuid class FibonacciRpcClient(object): def __init__(self): """ 客戶端啟動(dòng)時(shí),創(chuàng)建回調(diào)隊(duì)列,會(huì)開啟會(huì)話用于發(fā)送RPC請(qǐng)求以及接受響應(yīng) """ # 建立連接,指定服務(wù)器的ip地址 self.connection = pika.BlockingConnection(pika.ConnectionParameters( host='localhost')) # 建立一個(gè)會(huì)話,每個(gè)channel代表一個(gè)會(huì)話任務(wù) self.channel = self.connection.channel() # 聲明回調(diào)隊(duì)列,再次聲明的原因是,服務(wù)器和客戶端可能先后開啟,該聲明是冪等的,多次聲明,但只生效一次 result = self.channel.queue_declare(exclusive=True) # 將次隊(duì)列指定為當(dāng)前客戶端的回調(diào)隊(duì)列 self.callback_queue = result.method.queue # 客戶端訂閱回調(diào)隊(duì)列,當(dāng)回調(diào)隊(duì)列中有響應(yīng)時(shí),調(diào)用`on_response`方法對(duì)響應(yīng)進(jìn)行處理; self.channel.basic_consume(self.on_response, no_ack=True, queue=self.callback_queue) # 對(duì)回調(diào)隊(duì)列中的響應(yīng)進(jìn)行處理的函數(shù) def on_response(self, ch, method, props, body): if self.corr_id == props.correlation_id: self.response = body # 發(fā)出RPC請(qǐng)求 def call(self, n): # 初始化 response self.response = None #生成correlation_id self.corr_id = str(uuid.uuid4()) # 發(fā)送RPC請(qǐng)求內(nèi)容到RPC請(qǐng)求隊(duì)列`rpc_queue`,同時(shí)發(fā)送的還有`reply_to`和`correlation_id` self.channel.basic_publish(exchange='', routing_key='rpc_queue', properties=pika.BasicProperties( reply_to = self.callback_queue, correlation_id = self.corr_id, ), body=str(n)) while self.response is None: self.connection.process_data_events() return int(self.response) # 建立客戶端 fibonacci_rpc = FibonacciRpcClient() # 發(fā)送RPC請(qǐng)求 print(" [x] Requesting fib(30)") response = fibonacci_rpc.call(30) print(" [.] Got %r" % response)
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- Python rabbitMQ如何實(shí)現(xiàn)生產(chǎn)消費(fèi)者模式
- Python RabbitMQ實(shí)現(xiàn)簡(jiǎn)單的進(jìn)程間通信示例
- Python實(shí)現(xiàn)RabbitMQ6種消息模型的示例代碼
- Python隊(duì)列RabbitMQ 使用方法實(shí)例記錄
- python實(shí)現(xiàn)RabbitMQ的消息隊(duì)列的示例代碼
- python RabbitMQ 使用詳細(xì)介紹(小結(jié))
- Python RabbitMQ消息隊(duì)列實(shí)現(xiàn)rpc
- Python+Pika+RabbitMQ環(huán)境部署及實(shí)現(xiàn)工作隊(duì)列的實(shí)例教程
- 利用Python學(xué)習(xí)RabbitMQ消息隊(duì)列
- 基于python實(shí)現(xiàn)監(jiān)聽Rabbitmq系統(tǒng)日志代碼示例
相關(guān)文章
python實(shí)現(xiàn)在函數(shù)中修改變量值的方法
今天小編就為大家分享一篇python實(shí)現(xiàn)在函數(shù)中修改變量值的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-07-07Python基礎(chǔ)學(xué)習(xí)之基本數(shù)據(jù)結(jié)構(gòu)詳解【數(shù)字、字符串、列表、元組、集合、字典】
這篇文章主要介紹了Python基礎(chǔ)學(xué)習(xí)之基本數(shù)據(jù)結(jié)構(gòu),結(jié)合實(shí)例形式分析了Python數(shù)字、字符串、列表、元組、集合、字典等基本數(shù)據(jù)類型功能、原理及相關(guān)使用技巧,需要的朋友可以參考下2019-06-06Python數(shù)據(jù)類型之Tuple元組實(shí)例詳解
這篇文章主要介紹了Python數(shù)據(jù)類型之Tuple元組,結(jié)合實(shí)例形式分析了Python元組類型的概念、定義、讀取、連接、判斷等常見操作技巧與相關(guān)注意事項(xiàng),需要的朋友可以參考下2019-05-05Python?matplotlib如何簡(jiǎn)單繪制不同類型的表格
通過Matplotlib,開發(fā)者可以僅需要幾行代碼,便可以生成繪圖,直方圖,功率譜,條形圖,錯(cuò)誤圖,散點(diǎn)圖等,下面這篇文章主要給大家介紹了關(guān)于Python?matplotlib如何簡(jiǎn)單繪制不同類型表格的相關(guān)資料,需要的朋友可以參考下2022-07-07Python 異步之如何保護(hù)任務(wù)免于取消詳解
這篇文章主要為大家介紹了Python 異步之如何保護(hù)任務(wù)免于取消示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-03-03Python批量寫入ES索引數(shù)據(jù)的示例代碼
這篇文章主要為大家詳細(xì)介紹了如何使用python腳本批量寫ES數(shù)據(jù)(需要使用pip提前下載安裝es依賴庫(kù)),感興趣的小伙伴可以學(xué)習(xí)一下2024-02-02