python实现RabbitMQ同步跟异步消费模型

本文介绍了在Python中使用RabbitMQ进行消息推送和消费,重点讨论了同步和异步两种消费模式。同步消费可能会因未及时发送心跳导致连接中断,解决方案是创建心跳线程。而异步消费利用pika的select_connection方法,通过回调实现高效的消息处理,降低了ack次数,提高了效率。文中还给出了相关代码示例和参考资料。
摘要由CSDN通过智能技术生成

1,消息推送类

 1 import pika
 2 
 3 
 4 # 同步消息推送类
 5 class RabbitPublisher(object):
 6 
 7     # 传入RabbitMQ的ip,用户名,密码,实例化一个管道
 8     def __init__(self, host, user, password):
 9         self.host = host
10         self.user = user
11         self.password = password
12         self.connection = pika.BlockingConnection(pika.ConnectionParameters(host=self.host, credentials=pika.PlainCredentials(self.user, self.password)))
13         self.channel = self.connection.channel()
14 
15     # 发送消息在队列中
16     def send(self, queue_name, body):
17         self.channel.queue_declare(queue=queue_name, durable=True)  # 声明一个持久化队列
18         self.channel.basic_publish(exchange='',
19                                    routing_key=queue_name,  # 队列名字
20                                    body=body,  # 消息内容
21                                    properties=pika.BasicProperties(
22                                        delivery_mode=2,  # 消息持久化
23                                    ))
24 
25     # 清除指定队列的所有的消息
26     def purge(self, queue_name):
27         self.channel.queue_purge(queue_name)
28 
29     # 删除指定队列
30     def delete(self, queue_name, if_unused=False, if_empty=False):
31         self.channel.queue_delete(queue_name, if_unused=if_unused, if_empty=if_empty)
32 
33     # 断开连接
34     def stop(self):
35         self.connection.close()
View Code

2.消息消费类

(1)同步消息消费

 在同步消息消费的时候可能会出现pika库断开的情况,原因是因为pika客户端没有及时发送心跳,连接就被server端断开了。解决方案就是做一个心跳线程来维护连接。

心跳线程类

 1 class Heartbeat(threading.Thread):
 2 
 3     def __init__(self, connection):
 4         super(Heartbeat, self).__init__()
 5         self.lock = threading.Lock()  # 线程锁
 6         self.connection = connection  # rabbit连接
 7         self.quitflag = False  # 退出标志
 8         self.stopflag = True  # 暂停标志
 9         self.setDaemon(True)  # 设置为守护线程,当消息处理完,自动清除
10 
11     # 间隔10s发送心跳
12     def run(self):
13         while not self.quitflag:
14             time.sleep(10)  # 睡10s发一次心跳
15             self.lock.acquire()  # 加线程锁
16             if self.stopflag:
17                 self.lock.release()
18                 continue
19             try:
20                 self.connection.process_data_events()  # 一直等待服务段发来的消息
21             except Exception as e:
22                 print "Error format: %s" % (str(e))
23                 self.lock.release()
24                 return
25             self.lock.release()
26 
27     #
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在Python中集成RabbitMQ和FastAPI来实现异步消费消息,可以使用aio_pika库。 首先需要安装aio_pika和FastAPI: ``` pip install aio_pika fastapi ``` 然后可以使用以下代码作为示例: ```python from fastapi import FastAPI import aio_pika app = FastAPI() @app.on_event("startup") async def startup(): # 连接RabbitMQ connection = await aio_pika.connect_robust("amqp://guest:guest@localhost/") app.state.rabbitmq = connection @app.on_event("shutdown") async def shutdown(): # 关闭RabbitMQ连接 await app.state.rabbitmq.close() @app.get("/") async def read_root(): # 创建一个channel channel = await app.state.rabbitmq.channel() # 声明一个queue queue = await channel.declare_queue("my_queue") # 异步获取消息 async with queue.iterator() as queue_iter: async for message in queue_iter: async with message.process(): print(message.body) return {"status": "ok"} ``` 在上面的示例中,我们在FastAPI的startup事件中连接到RabbitMQ,并将连接保存在app.state.rabbitmq中。在shutdown事件中关闭连接。 在read_root函数中,我们创建一个channel并声明一个queue。然后使用queue.iterator()方法获取一个异步迭代器,并使用async for循环异步获取消息。在异步获取到消息后,我们使用message.process()方法来确认消息已经被处理。 当然,在实际应用中,你可能需要根据具体的业务场景来编写更加复杂的代码。不过,以上代码可以作为一个很好的起点来帮助你快速集成RabbitMQ和FastAPI。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值