侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

python实现RabbitMQ的消息队列的示例代码

Python  /  管理员 发布于 7年前   278

最近在研究redis做消息队列时,顺便看了一下RabbitMQ做消息队列的实现。以下是总结的RabbitMQ中三种exchange模式的实现,分别是fanout, direct和topic。

base.py:

import pika# 获取认证对象,参数是用户名、密码。远程连接时需要认证credentials = pika.PlainCredentials("admin", "admin")# BlockingConnection(): 实例化连接对象# ConnectionParameters(): 实例化链接参数对象connection = pika.BlockingConnection(pika.ConnectionParameters(  "192.168.0.102", 5672, "/", credentials))# 创建新的channel(通道)channel = connection.channel()

fanout模式:向绑定到指定exchange的queue中发送消息,消费者从queue中取出数据,类似于广播模式、发布订阅模式。
绑定方式: 在接收端channel.queue_bind(exchange="logs", queue=queue_name)

代码:

publisher.py:

from base import channel, connection# 声明exchange, 不声明queuechannel.exchange_declare(exchange="logs", exchange_type="fanout") # 广播message = "hello fanout"channel.basic_publish(  exchange="logs",  routing_key="",  body=message)connection.close()

consumer.py:

from base import channel, connection    # 声明exchangechannel.exchange_declare(exchange="logs", exchange_type="fanout")# 不指定queue名字, rabbitmq会随机分配一个名字, 消息处理完成后queue会自动删除result = channel.queue_declare(exclusive=True) # 获取queue名字queue_name = result.method.queue# 绑定exchange和queuechannel.queue_bind(exchange="logs", queue=queue_name)def callback(ch, method, properties, body):  print("body:%s" % body)channel.basic_consume(  callback,  queue=queue_name)channel.start_consuming()

direct模式:发送端绑定一个routing_key1, queue中绑定若干个routing_key2, 若key1与key2相等,或者key1在key2中,则消息就会发送到这个queue中,再由相应的消费者去queue中取数据。

publisher.py:

from base import channel, connectionchannel.exchange_declare(exchange="direct_test", exchange_type="direct")message = "hello"channel.basic_publish(  exchange="direct_test",  routing_key="info", # 绑定key  body=message)connection.close()

consumer01.py:

from base import channel, connectionchannel.exchange_declare(exchange="direct_test", exchange_type="direct")result = channel.queue_declare(exclusive=True)queue_name = result.method.queuechannel.queue_bind(  exchange="direct_test",  queue=queue_name,  # 绑定的key,与publisher中的相同  routing_key="info" )def callback(ch, method, properties, body):  print("body:%s" % body)channel.basic_consume(  callback,  queue=queue_name)channel.start_consuming()

consumer02.py:

from base import channel, connectionchannel.exchange_declare(exchange="direct_test", exchange_type="direct")result = channel.queue_declare(exclusive=True)queue_name = result.method.queuechannel.queue_bind(  exchange="direct_test",  queue=queue_name,  # 绑定的key  routing_key="error"  )def callback(ch, method, properties, bosy):  print("body:%s" % body)channel.basic_consume(  callback,  queue=queue_name)channel.start_consuming()

consumer03.py:

from base import channel, connectionchannel.exchange_declare(exchange="direct_test", exchange_type="direct")result = channel.queue_declare(exclusive=True)queue_name = result.method.queuekey_list = ["info", "warning"]for key in key_list:  channel.queue_bind(    exchange="direct_test",    queue=queue_name,    # 一个queue同时绑定多个key,有一个key满足条件时就可以收到数据    routing_key=key   )def callback(ch, method, properties, body):  print("body:%s" % body)channel.basic_consume(  callback,  queue=queue_name)channel.start_consuming()

执行:

python producer.pypython consumer01.pypython consumer02.pypython consumer03.py

结果:

consumer01.py: body:b'hello'
consumer02.py没收到结果
consumer03.py: body:b'hello'

topic模式不是太好理解,我的理解如下:

对于发送端绑定的routing_key1,queue绑定若干个routing_key2;若routing_key1满足任意一个routing_key2,则该消息就会通过exchange发送到这个queue中,然后由接收端从queue中取出其实就是direct模式的扩展。

绑定方式:

发送端绑定:

  channel.basic_publish(    exchange="topic_logs",    routing_key=routing_key,    body=message  )

接收端绑定:

  channel.queue_bind(    exchange="topic_logs",    queue=queue_name,    routing_key=binding_key  )

publisher.py:

import sysfrom base import channel, connection# 声明exchangechannel.exchange_declare(exchange="topic_test", exchange_type="topic")# 待发送消息message = " ".join(sys.argv[1:]) or "hello topic"# 发布消息channel.basic_publish(  exchange="topic_test",  routing_key="mysql.error",  # 绑定的routing_key  body=message)connection.close()

consumer01.py:

from base import channel, connectionchannel.exchange_declare(exchange="topic_test", exchange_type="topic")result = channel.queue_declare(exclusive=True)queue_name = result.method.queuechannel.queue_bind(  exchange="topic_test",  queue=queue_name,  routing_key="*.error"  # 绑定的routing_key)def callback(ch, method, properties, body):  print("body:%s" % body)channel.basic_consume(  callback,  queue=queue_name,  no_ack=True)channel.start_consuming()

consumer02.py:

from base import channel, connectionchannel.exchange_declare(exchange="topic_test", exchange_type="topic")result = channel.queue_declare(exclusive=True)queue_name = result.method.queuechannel.queue_bind(  exchange="topic_test",  queue=queue_name,  routing_key="mysql.*"  # 绑定的routing_key)def callback(ch, method, properties, body):  print("body:%s" % body)channel.basic_consume(  callback,  queue=queue_name,  no_ack=True)channel.start_consuming()

执行:

python publisher02.py "this is a topic test"python consumer01.pypython consumer02.py

结果:

consumer01.py的结果: body:b'this is a topic test'
consumer02.py的结果: body:b'this is a topic test'

说明通过绑定相应的routing_key,两个消费者都收到了消息

将publisher.py的routing_key改成"mysql.info"

再此执行:

python publisher02.py "this is a topic test"python consumer01.pypython consumer02.py

结果:

consumer01.py没收到结果
consumer02.py的结果: body:b'this is a topic test'

通过这个例子我们就能明白topic的运行方式了。

参考自: https:///article/150386.htm

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。


  • 上一条:
    在Python中实现shuffle给列表洗牌
    下一条:
    对Python 3.5拼接列表的新语法详解
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在python语言中Flask框架的学习及简单功能示例(0个评论)
    • 在Python语言中实现GUI全屏倒计时代码示例(0个评论)
    • Python + zipfile库实现zip文件解压自动化脚本示例(0个评论)
    • python爬虫BeautifulSoup快速抓取网站图片(1个评论)
    • vscode 配置 python3开发环境的方法(0个评论)
    • 近期文章
    • 智能合约Solidity学习CryptoZombie第三课:组建僵尸军队(高级Solidity理论)(0个评论)
    • 智能合约Solidity学习CryptoZombie第二课:让你的僵尸猎食(0个评论)
    • 智能合约Solidity学习CryptoZombie第一课:生成一只你的僵尸(0个评论)
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2018-04
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2022-01
    • 2023-07
    • 2023-10
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客