如何使用 Python 中的 stomp 库从队列中读取所有消息?

Posted

技术标签:

【中文标题】如何使用 Python 中的 stomp 库从队列中读取所有消息?【英文标题】:How to read all message from queue using stomp library in Python? 【发布时间】:2017-04-12 08:38:41 【问题描述】:

如何在 Python 中读取 stomp 队列中的所有消息?

我写了这样的代码,但它只读取一条消息并且存在 - 如何强制读取所有消息。

# 编码=utf-8 进口跺脚 导入日志 从 medptr.farm.farm 导入 FarmSettings 进口平台 导入操作系统 如果 __name__ == '__main__': logging.basicConfig(level=logging.DEBUG) 记录器 = logging.getLogger(__name__) 类 ConnectionListener(stomp.ConnectionListener): def __init__(自我,连接): self.connection = 连接 “当前连接。” def on_error(self, headers, body): 记录器 = logging.getLogger(__name__) logger.error('Stomp 连接错误 headers = %s and body = %s.' % (headers, body)) def on_message(self, headers, message): 记录器 = logging.getLogger(__name__) logger.debug('Stomp new message headers = %s and body = %s.' % (headers, message)) 农场 = FarmSettings.get_by_hostname() conn = stomp.Connection12(host_and_ports=farm.active_mq_settings.hosts_and_ports) conn.set_listener('消息', ConnectionListener(conn)) conn.set_listener('print', stomp.PrintingListener()) conn.set_listener('stats', stomp.StatsListener()) conn.start() conn.connect(用户名=farm.active_mq_settings.username,密码=farm.active_mq_settings.passcode,等待=真) subscribe_id = '-'.join(map(str, (platform.node(), os.getppid(), os.getpid()))) # conn.set_listener('stats', stomp.StatsListener()) # conn.set_listener('print', stomp.PrintingListener()) conn.send('队列/测试', '你好') conn.subscribe(destination='queue/test', id=subscribe_id, ack='client-individual') conn.unsubscribe(id=subscribe_id) 连接断开() conn.stop()

【问题讨论】:

【参考方案1】:

您可以使用 Stomp 库中的 TestListner:

conn = stomp.Connection([(host, 61613)]) #This is the default stomp port
listener = TestListener()
conn.set_listener('', listener)
conn.start()
conn.connect(username, password, wait=True)
conn.subscribe(destination=queue_name, id=1, ack='auto')
listener.message_list #This can read all the messages from the queue
headers, message = listener.get_latest_message() #This can read the last message from the queue
conn.unsubscribe(queue_name)
conn.disconnect()   

【讨论】:

以上是关于如何使用 Python 中的 stomp 库从队列中读取所有消息?的主要内容,如果未能解决你的问题,请参考以下文章

使用 Rabbitmq STOMP websocket 获取队列大小

使用队列的 C# STOMP 消息传递

我如何限制发送到Stomp队列(处理websocket)的数据量,以便可以保证不会溢出缓冲区?

使用持久队列 STOMP 向离线用户发送通知

如何将事务与 Stomp 和 ActiveMQ(和 Perl)一起使用?

activemq如何配置在python中使用stomp