电脑知识|欧美黑人一区二区三区|软件|欧美黑人一级爽快片淫片高清|系统|欧美黑人狂野猛交老妇|数据库|服务器|编程开发|网络运营|知识问答|技术教程文章 - 好吧啦网

您的位置:首頁技術文章
文章詳情頁

Python實現RabbitMQ6種消息模型的示例代碼

瀏覽:8日期:2022-07-31 17:26:40

RabbitMQ與Redis對比

​ RabbitMQ是一種比較流行的消息中間件,之前我一直使用redis作為消息中間件,但是生產環境比較推薦RabbitMQ來替代Redis,所以我去查詢了一些RabbitMQ的資料。相比于Redis,RabbitMQ優點很多,比如:

具有消息消費確認機制 隊列,消息,都可以選擇是否持久化,粒度更小、更靈活。 可以實現負載均衡

RabbitMQ應用場景

異步處理:比如用戶注冊時的確認郵件、短信等交由rabbitMQ進行異步處理 應用解耦:比如收發消息雙方可以使用消息隊列,具有一定的緩沖功能 流量削峰:一般應用于秒殺活動,可以控制用戶人數,也可以降低流量 日志處理:將info、warning、error等不同的記錄分開存儲

RabbitMQ消息模型

​ 這里使用 Pythonpika 這個庫來實現RabbitMQ中常見的6種消息模型。沒有的可以先安裝:

pip install pika

1.單生產單消費模型:即完成基本的一對一消息轉發。

Python實現RabbitMQ6種消息模型的示例代碼

# 生產者代碼import pikacredentials = pika.PlainCredentials(’chuan’, ’123’) # mq用戶名和密碼,沒有則需要自己創建# 虛擬隊列需要指定參數 virtual_host,如果是默認的可以不填。connection = pika.BlockingConnection(pika.ConnectionParameters(host=’localhost’,port=5672,virtual_host=’/’,credentials=credentials))# 建立rabbit協議的通道channel = connection.channel()# 聲明消息隊列,消息將在這個隊列傳遞,如不存在,則創建。durable指定隊列是否持久化channel.queue_declare(queue=’python-test’, durable=False)# message不能直接發送給queue,需經exchange到達queue,此處使用以空字符串標識的默認的exchange# 向隊列插入數值 routing_key是隊列名channel.basic_publish(exchange=’’, routing_key=’python-test’, body=’Hello world!2’)# 關閉與rabbitmq server的連接connection.close()

# 消費者代碼import pikacredentials = pika.PlainCredentials(’chuan’, ’123’)# BlockingConnection:同步模式connection = pika.BlockingConnection(pika.ConnectionParameters(host=’localhost’,port=5672,virtual_host=’/’, credentials=credentials))channel = connection.channel()# 申明消息隊列。當不確定生產者和消費者哪個先啟動時,可以兩邊重復聲明消息隊列。channel.queue_declare(queue=’python-test’, durable=False)# 定義一個回調函數來處理消息隊列中的消息,這里是打印出來def callback(ch, method, properties, body): # 手動發送確認消息 ch.basic_ack(delivery_tag=method.delivery_tag) print(body.decode()) # 告訴生產者,消費者已收到消息# 告訴rabbitmq,用callback來接收消息# 默認情況下是要對消息進行確認的,以防止消息丟失。# 此處將auto_ack明確指明為True,不對消息進行確認。channel.basic_consume(’python-test’, on_message_callback=callback) # auto_ack=True) # 自動發送確認消息# 開始接收信息,并進入阻塞狀態,隊列里有信息才會調用callback進行處理channel.start_consuming()

2.消息分發模型:多個收聽者監聽一個隊列。

Python實現RabbitMQ6種消息模型的示例代碼

# 生產者代碼import pikacredentials = pika.PlainCredentials(’chuan’, ’123’) # mq用戶名和密碼# 虛擬隊列需要指定參數 virtual_host,如果是默認的可以不填。connection = pika.BlockingConnection(pika.ConnectionParameters(host=’localhost’,port=5672,virtual_host=’/’,credentials=credentials))# 建立rabbit協議的通道channel = connection.channel()# 聲明消息隊列,消息將在這個隊列傳遞,如不存在,則創建。durable指定隊列是否持久化。確保沒有確認的消息不會丟失channel.queue_declare(queue=’rabbitmqtest’, durable=True)# message不能直接發送給queue,需經exchange到達queue,此處使用以空字符串標識的默認的exchange# 向隊列插入數值 routing_key是隊列名# basic_publish的properties參數指定message的屬性。此處delivery_mode=2指明message為持久的for i in range(10): channel.basic_publish(exchange=’’, routing_key=’python-test’, body=’Hello world!%s’ % i, properties=pika.BasicProperties(delivery_mode=2))# 關閉與rabbitmq server的連接connection.close()

# 消費者代碼,consume1與consume2import pikaimport timecredentials = pika.PlainCredentials(’chuan’, ’123’)# BlockingConnection:同步模式connection = pika.BlockingConnection(pika.ConnectionParameters(host=’localhost’,port=5672,virtual_host=’/’,credentials=credentials))channel = connection.channel()# 申明消息隊列。當不確定生產者和消費者哪個先啟動時,可以兩邊重復聲明消息隊列。channel.queue_declare(queue=’rabbitmqtest’, durable=True)# 定義一個回調函數來處理消息隊列中的消息,這里是打印出來def callback(ch, method, properties, body): # 手動發送確認消息 time.sleep(10) print(body.decode()) # 告訴生產者,消費者已收到消息 ch.basic_ack(delivery_tag=method.delivery_tag)# 如果該消費者的channel上未確認的消息數達到了prefetch_count數,則不向該消費者發送消息channel.basic_qos(prefetch_count=1)# 告訴rabbitmq,用callback來接收消息# 默認情況下是要對消息進行確認的,以防止消息丟失。# 此處將no_ack明確指明為True,不對消息進行確認。channel.basic_consume(’python-test’, on_message_callback=callback) # auto_ack=True) # 自動發送確認消息# 開始接收信息,并進入阻塞狀態,隊列里有信息才會調用callback進行處理channel.start_consuming()

3.fanout消息訂閱模式:生產者將消息發送到Exchange,Exchange再轉發到與之綁定的Queue中,每個消費者再到自己的Queue中取消息。

Python實現RabbitMQ6種消息模型的示例代碼

# 生產者代碼import pikacredentials = pika.PlainCredentials(’chuan’, ’123’) # mq用戶名和密碼# 虛擬隊列需要指定參數 virtual_host,如果是默認的可以不填。connection = pika.BlockingConnection(pika.ConnectionParameters(host=’localhost’,port=5672,virtual_host=’/’,credentials=credentials))# 建立rabbit協議的通道channel = connection.channel()# fanout: 所有綁定到此exchange的queue都可以接收消息(實時廣播)# direct: 通過routingKey和exchange決定的那一組的queue可以接收消息(有選擇接受)# topic: 所有符合routingKey(此時可以是一個表達式)的routingKey所bind的queue可以接收消息(更細致的過濾)channel.exchange_declare(’logs’, exchange_type=’fanout’)#因為是fanout廣播類型的exchange,這里無需指定routing_keyfor i in range(10): channel.basic_publish(exchange=’logs’, routing_key=’’, body=’Hello world!%s’ % i)# 關閉與rabbitmq server的連接connection.close()

import pikacredentials = pika.PlainCredentials(’chuan’, ’123’)# BlockingConnection:同步模式connection = pika.BlockingConnection(pika.ConnectionParameters(host=’localhost’,port=5672,virtual_host=’/’,credentials=credentials))channel = connection.channel()#作為好的習慣,在producer和consumer中分別聲明一次以保證所要使用的exchange存在channel.exchange_declare(exchange=’logs’, exchange_type=’fanout’)# 隨機生成一個新的空的queue,將exclusive置為True,這樣在consumer從RabbitMQ斷開后會刪除該queue# 是排他的。result = channel.queue_declare(’’, exclusive=True)# 用于獲取臨時queue的namequeue_name = result.method.queue# exchange與queue之間的關系成為binding# binding告訴exchange將message發送該哪些queuechannel.queue_bind(exchange=’logs’, queue=queue_name)# 定義一個回調函數來處理消息隊列中的消息,這里是打印出來def callback(ch, method, properties, body): # 手動發送確認消息 print(body.decode()) # 告訴生產者,消費者已收到消息 #ch.basic_ack(delivery_tag=method.delivery_tag)# 如果該消費者的channel上未確認的消息數達到了prefetch_count數,則不向該消費者發送消息channel.basic_qos(prefetch_count=1)# 告訴rabbitmq,用callback來接收消息# 默認情況下是要對消息進行確認的,以防止消息丟失。# 此處將no_ack明確指明為True,不對消息進行確認。channel.basic_consume(queue=queue_name, on_message_callback=callback, auto_ack=True) # 自動發送確認消息# 開始接收信息,并進入阻塞狀態,隊列里有信息才會調用callback進行處理channel.start_consuming()

4.direct路由模式:此時生產者發送消息時需要指定RoutingKey,即路由Key,Exchange接收到消息時轉發到與RoutingKey相匹配的隊列中。

Python實現RabbitMQ6種消息模型的示例代碼

# 生產者代碼,測試命令可以使用:python produce.py error 404errorimport pikaimport sysconnection = pika.BlockingConnection(pika.ConnectionParameters(host=’localhost’))channel = connection.channel()# 聲明一個名為direct_logs的direct類型的exchange# direct類型的exchangechannel.exchange_declare(exchange=’direct_logs’, exchange_type=’direct’)# 從命令行獲取basic_publish的配置參數severity = sys.argv[1] if len(sys.argv) > 1 else ’info’message = ’ ’.join(sys.argv[2:]) or ’Hello World!’# 向名為direct_logs的exchage按照設置的routing_key發送messagechannel.basic_publish(exchange=’direct_logs’, routing_key=severity, body=message)print(' [x] Sent %r:%r' % (severity, message))connection.close()

# 消費者代碼,測試可以使用:python consume.py errorimport pikaimport sysconnection = pika.BlockingConnection(pika.ConnectionParameters(host=’localhost’))channel = connection.channel()# 聲明一個名為direct_logs類型為direct的exchange# 同時在producer和consumer中聲明exchage或queue是個好習慣,以保證其存在channel.exchange_declare(exchange=’direct_logs’, exchange_type=’direct’)result = channel.queue_declare(’’, exclusive=True)queue_name = result.method.queue# 從命令行獲取參數:routing_keyseverities = sys.argv[1:]if not severities: print(sys.stderr, 'Usage: %s [info] [warning] [error]' % (sys.argv[0],)) sys.exit(1)for severity in severities: # exchange和queue之間的binding可接受routing_key參數 # fanout類型的exchange直接忽略該參數。direct類型的exchange精確匹配該關鍵字進行message路由 # 一個消費者可以綁定多個routing_key # Exchange就是根據這個RoutingKey和當前Exchange所有綁定的BindingKey做匹配, # 如果滿足要求,就往BindingKey所綁定的Queue發送消息 channel.queue_bind(exchange=’direct_logs’, queue=queue_name, routing_key=severity)def callback(ch, method, properties, body): print(' [x] %r:%r' % (method.routing_key, body,))channel.basic_consume(queue=queue_name, on_message_callback=callback, auto_ack=True)channel.start_consuming()

5.topic匹配模式:更細致的分組,允許在RoutingKey中使用匹配符。

*:匹配一個單詞 #:匹配0個或多個單詞

Python實現RabbitMQ6種消息模型的示例代碼

# 生產者代碼,基本不變,只需將exchange_type改為topic(測試:python produce.py rabbitmq.red # red color is my favoriteimport pikaimport sysconnection = pika.BlockingConnection(pika.ConnectionParameters(host=’localhost’))channel = connection.channel()# 聲明一個名為direct_logs的direct類型的exchange# direct類型的exchangechannel.exchange_declare(exchange=’topic_logs’, exchange_type=’topic’)# 從命令行獲取basic_publish的配置參數severity = sys.argv[1] if len(sys.argv) > 1 else ’info’message = ’ ’.join(sys.argv[2:]) or ’Hello World!’# 向名為direct_logs的exchange按照設置的routing_key發送messagechannel.basic_publish(exchange=’topic_logs’, routing_key=severity, body=message)print(' [x] Sent %r:%r' % (severity, message))connection.close()

# 消費者代碼,(測試:python consume.py *.red)import pikaimport sysconnection = pika.BlockingConnection(pika.ConnectionParameters(host=’localhost’))channel = connection.channel()# 聲明一個名為direct_logs類型為direct的exchange# 同時在producer和consumer中聲明exchage或queue是個好習慣,以保證其存在channel.exchange_declare(exchange=’topic_logs’, exchange_type=’topic’)result = channel.queue_declare(’’, exclusive=True)queue_name = result.method.queue# 從命令行獲取參數:routing_keyseverities = sys.argv[1:]if not severities: print(sys.stderr, 'Usage: %s [info] [warning] [error]' % (sys.argv[0],)) sys.exit(1)for severity in severities: # exchange和queue之間的binding可接受routing_key參數 # fanout類型的exchange直接忽略該參數。direct類型的exchange精確匹配該關鍵字進行message路由 # 一個消費者可以綁定多個routing_key # Exchange就是根據這個RoutingKey和當前Exchange所有綁定的BindingKey做匹配, # 如果滿足要求,就往BindingKey所綁定的Queue發送消息 channel.queue_bind(exchange=’topic_logs’, queue=queue_name, routing_key=severity)def callback(ch, method, properties, body): print(' [x] %r:%r' % (method.routing_key, body,))channel.basic_consume(queue=queue_name, on_message_callback=callback, auto_ack=True)channel.start_consuming()

6.RPC遠程過程調用:客戶端與服務器之間是完全解耦的,即兩端既是消息的發送者也是接受者。

Python實現RabbitMQ6種消息模型的示例代碼

# 生產者代碼import pikaimport uuid# 在一個類中封裝了connection建立、queue聲明、consumer配置、回調函數等class FibonacciRpcClient(object): def __init__(self): # 建立到RabbitMQ Server的connection self.connection = pika.BlockingConnection(pika.ConnectionParameters(host=’localhost’)) self.channel = self.connection.channel() # 聲明一個臨時的回調隊列 result = self.channel.queue_declare(’’, exclusive=True) self._queue = result.method.queue # 此處client既是producer又是consumer,因此要配置consume參數 # 這里的指明從client自己創建的臨時隊列中接收消息 # 并使用on_response函數處理消息 # 不對消息進行確認 self.channel.basic_consume(queue=self._queue, on_message_callback=self.on_response, auto_ack=True) self.response = None self.corr_id = None # 定義回調函數 # 比較類的corr_id屬性與props中corr_id屬性的值 # 若相同則response屬性為接收到的message def on_response(self, ch, method, props, body): if self.corr_id == props.correlation_id: self.response = body def call(self, n): # 初始化response和corr_id屬性 self.corr_id = str(uuid.uuid4()) # 使用默認exchange向server中定義的rpc_queue發送消息 # 在properties中指定replay_to屬性和correlation_id屬性用于告知遠程server # correlation_id屬性用于匹配request和response self.channel.basic_publish(exchange=’’, routing_key=’rpc_queue’, properties=pika.BasicProperties( reply_to=self._queue, correlation_id=self.corr_id, ), # message需為字符串 body=str(n)) while self.response is None: self.connection.process_data_events() return int(self.response)# 生成類的實例fibonacci_rpc = FibonacciRpcClient()print(' [x] Requesting fib(30)')# 調用實例的call方法response = fibonacci_rpc.call(30)print(' [.] Got %r' % response)

# 消費者代碼,這里以生成斐波那契數列為例import pika# 建立到達RabbitMQ Server的connectionconnection = pika.BlockingConnection(pika.ConnectionParameters(host=’localhost’))channel = connection.channel()# 聲明一個名為rpc_queue的queuechannel.queue_declare(queue=’rpc_queue’)# 計算指定數字的斐波那契數def fib(n): if n == 0: return 0 elif n == 1: return 1 else: return fib(n - 1) + fib(n - 2)# 回調函數,從queue接收到message后調用該函數進行處理def on_request(ch, method, props, body): # 由message獲取要計算斐波那契數的數字 n = int(body) print(' [.] fib(%s)' % n) # 調用fib函數獲得計算結果 response = fib(n) # exchage為空字符串則將message發送個到routing_key指定的queue # 這里queue為回調函數參數props中reply_ro指定的queue # 要發送的message為計算所得的斐波那契數 # properties中correlation_id指定為回調函數參數props中co的rrelation_id # 最后對消息進行確認 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)# 只有consumer已經處理并確認了上一條message時queue才分派新的message給它channel.basic_qos(prefetch_count=1)# 設置consumeer參數,即從哪個queue獲取消息使用哪個函數進行處理,是否對消息進行確認channel.basic_consume(queue=’rpc_queue’, on_message_callback=on_request)print(' [x] Awaiting RPC requests')# 開始接收并處理消息channel.start_consuming()

到此這篇關于Python實現RabbitMQ6種消息模型的示例代碼的文章就介紹到這了,更多相關Python RabbitMQ消息模型 內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!

標簽: Python 編程
相關文章:
主站蜘蛛池模板: 超细|超微气流粉碎机|气流磨|气流分级机|粉体改性机|磨粉机|粉碎设备-山东埃尔派粉体科技 | 砂石生产线_石料生产线设备_制砂生产线设备价格_生产厂家-河南中誉鼎力智能装备有限公司 | 胶原检测试剂盒,弹性蛋白检测试剂盒,类克ELISA试剂盒,阿达木单抗ELISA试剂盒-北京群晓科苑生物技术有限公司 | 纸张环压仪-纸张平滑度仪-杭州纸邦自动化技术有限公司 | 精密五金冲压件_深圳五金冲压厂_钣金加工厂_五金模具加工-诚瑞丰科技股份有限公司 | 农产品溯源系统_农产品质量安全追溯系统_溯源系统| 武汉天安盾电子设备有限公司 - 安盾安检,武汉安检门,武汉安检机,武汉金属探测器,武汉测温安检门,武汉X光行李安检机,武汉防爆罐,武汉车底安全检查,武汉液体探测仪,武汉安检防爆设备 | 冲击式破碎机-冲击式制砂机-移动碎石机厂家_青州市富康机械有限公司 | 电伴热系统施工_仪表电伴热保温箱厂家_沃安电伴热管缆工业技术(济南)有限公司 | 粉末冶金-粉末冶金齿轮-粉末冶金零件厂家-东莞市正朗精密金属零件有限公司 | CCE素质教育博览会 | CCE素博会 | 教育展 | 美育展 | 科教展 | 素质教育展 | 工业废水处理|污水处理厂|废水治理设备工程技术公司-苏州瑞美迪 今日娱乐圈——影视剧集_八卦娱乐_明星八卦_最新娱乐八卦新闻 | 玻璃钢格栅盖板|玻璃钢盖板|玻璃钢格栅板|树篦子-长沙川皖玻璃钢制品有限公司 | 低压载波电能表-单相导轨式电能表-华邦电力科技股份有限公司-智能物联网综合管理平台 | 航空连接器,航空插头,航空插座,航空接插件,航插_深圳鸿万科 | 国际线缆连接网 - 连接器_线缆线束加工行业门户网站 | 北京软件开发_软件开发公司_北京软件公司-北京宜天信达软件开发公司 | 不锈钢闸阀_球阀_蝶阀_止回阀_调节阀_截止阀-可拉伐阀门(上海)有限公司 | 一航网络-软件测评官网 | 广州物流公司_广州货运公司_广州回程车运输 - 万信物流 | 礼堂椅厂家|佛山市艺典家具有限公司 | 精益专家 - 设备管理软件|HSE管理系统|设备管理系统|EHS安全管理系统 | 油漆辅料厂家_阴阳脚线_艺术漆厂家_内外墙涂料施工_乳胶漆专用防霉腻子粉_轻质粉刷石膏-魔法涂涂 | 英国公司注册-新加坡公司注册-香港公司开户-离岸公司账户-杭州商标注册-杭州优创企业 | 橡胶接头|可曲挠橡胶接头|橡胶软接头安装使用教程-上海松夏官方网站 | 冷油器,取样冷却器,热力除氧器-连云港振辉机械设备有限公司 | 执业药师报名条件,考试时间,考试真题,报名入口—首页 | 紫外可见光分光度计-紫外分光度计-分光光度仪-屹谱仪器制造(上海)有限公司 | 山东锐智科电检测仪器有限公司_超声波测厚仪,涂层测厚仪,里氏硬度计,电火花检漏仪,地下管线探测仪 | 专注提供国外机电设备及配件-工业控制领域一站式服务商-深圳市华联欧国际贸易有限公司 | 金属清洗剂,防锈油,切削液,磨削液-青岛朗力防锈材料有限公司 | 杭州用友|用友软件|用友财务软件|用友ERP系统--杭州协友软件官网 | 济南铝方通-济南铝方通价格-济南方通厂家-山东鲁方通建材有限公司 | Safety light curtain|Belt Sway Switches|Pull Rope Switch|ultrasonic flaw detector-Shandong Zhuoxin Machinery Co., Ltd | AGV无人叉车_激光叉车AGV_仓储AGV小车_AGV无人搬运车-南昌IKV机器人有限公司[官网] | 南京PVC快速门厂家南京快速卷帘门_南京pvc快速门_世界500强企业国内供应商_南京美高门业 | 步进驱动器「一体化」步进电机品牌厂家-一体式步进驱动 | 动环监控_机房环境监控_DCIM_机房漏水检测-斯特纽 | 中国品牌排名投票_十大品牌榜单_中国著名品牌【中国品牌榜】 | 鲁尔圆锥接头多功能测试仪-留置针测试仪-上海威夏环保科技有限公司 | 进口消泡剂-道康宁消泡剂-陶氏消泡剂-大洋消泡剂 |