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