You need to enable JavaScript to run this app. Qpid Proton Python复用连接批量发消息 避免频繁开闭连接
优惠活动
大模型
产品
解决方案
定价
更多

Qpid Proton Python复用连接批量发消息 避免频繁开闭连接

基于Qpid Proton实现单连接复用发送多条消息的方案

Qpid Proton采用事件驱动架构,官方提供的单条消息发送示例是最小演示用例,实际生产环境可以通过维护长连接、缓存待发送队列的方式实现连接复用,避免每次发送消息都重建连接的性能损耗。

核心实现逻辑如下:

  • 将连接、Sender实例作为Handler的全局属性,仅在on_start生命周期中初始化一次,不随单条消息发送销毁
  • 新增待发送消息缓存队列,对外暴露添加消息的接口,收到新消息后存入队列等待发送
  • 移除on_sendable方法中发送完成就关闭Sender、关闭连接的逻辑,Sender可用时自动从缓存队列拉取消息批量发送

完整示例代码如下:

import json
from proton import Message
from proton.handlers import MessagingHandler
from proton.reactor import Container

# 替换为实际的Broker地址和目标队列/Topic地址
HOST = "amqp://localhost:5672"
ADDRESS = "test_queue"

class ReusableMessageHandler(MessagingHandler):
    def __init__(self):
        super().__init__()
        self.conn_url = HOST
        self.address = ADDRESS
        # 待发送消息缓存队列
        self.pending_messages = []
        self.sender = None
        self.connection = None
        # 关闭标记,需要停止服务时设为True
        self.shutdown_flag = False

    def add_message(self, msg_body: dict):
        """对外暴露的添加待发送消息接口,支持运行时动态新增消息"""
        self.pending_messages.append(json.dumps(msg_body))

    def on_start(self, event):
        # 启动时仅创建一次连接和Sender
        self.connection = event.container.connect(self.conn_url)
        self.sender = event.container.create_sender(self.connection, self.address)

    def on_sendable(self, event):
        # Sender有可用发送额度时,批量发送所有待发送消息
        while self.pending_messages and event.sender.credit > 0:
            current_msg = self.pending_messages.pop(0)
            event.sender.send(Message(body=current_msg))
        # 开启关闭标记且所有消息发送完成后,再销毁资源
        if self.shutdown_flag and not self.pending_messages:
            event.sender.close()
            self.connection.close()

# 使用示例
if __name__ == "__main__":
    handler = ReusableMessageHandler()
    # 批量添加3条消息,共用同一个连接发送
    handler.add_message({"title": "test_msg_1"})
    handler.add_message({"title": "test_msg_2"})
    handler.add_message({"title": "test_msg_3"})
    # 所有消息发送完成后关闭连接
    handler.shutdown_flag = True
    # 启动事件循环执行发送
    Container(handler).run()

如果是需要长期运行的消息生产者服务,不需要设置shutdown_flag,保持事件循环常驻即可,有新消息要发送时直接调用add_message方法加入队列,框架会自动触发后续发送流程,全程复用同一个连接和Sender实例。

内容的提问来源于stack exchange,提问作者Max Kossatz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.14 07:45:04