python接收ActiveMQ消息

最近项目需要用到ActiveMQ,使用topic接收消息,网上搜到的例子,发送都没有问题,把conn.start()函数注释掉就ok了,但是接收消息的函数总是报message不存在。

    notify_func(frame)
TypeError: on_message() missing 1 required positional argument: 'message' 

经过检查发现新版本的stomp函数on_message()变了,由之前的3个参数变成了2个参数。

修改代码就能够正常接收了,代码如下:

    def on_message(self, frame):
        print(f"message: headers:{frame.headers['destination']}, message:{frame.body}")

好的,可以尝试使用pymqi和stomp.py这两个库来实现。首先安装这两个库:pip install pymqi stomp.py 然后使用pymqi连接到ActiveMQ,在连接成功后,使用stomp.py订阅消息,可以按照以下代码示例来实现: ```python import stomp import pymqi host = 'localhost' port = '61613' channel = 'SYSTEM.ADMIN.SVRCONN' queue_manager = 'QM' queue_name = 'QUEUE.NAME' class MQListener(stomp.ConnectionListener): def on_message(self, headers, message): print('Received message: {}'.format(message)) def on_error(self, headers, message): print('Error received: {}'.format(message)) conn = stomp.Connection(host_and_ports=[(host, port)]) conn.set_listener('', MQListener()) queue_manager = pymqi.connect(queue_manager, channel, '{}({})'.format(host, port)) queue = pymqi.Queue(queue_manager, queue_name) queue.get() pymqi.disconnect(queue_manager) conn.subscribe(destination='/queue/{}'.format(queue_name), id=1, ack='auto') conn.start() conn.connect() while True: pass ``` 这段代码中,我们首先定义了一个MQListener类,用于接收消息后打印消息内容。然后创建了一个Connection对象,使用set_listener()方法将MQListener对象加入进去。使用pymqi连接到ActiveMQ,通过Queue.get()方法获取一条消息后,执行pymqi.disconnect()方法退出连接。接着使用stomp.py的subscribe()方法订阅消息,使用start()方法启动连接,然后进入死循环等待消息的到来,当有消息到来时就会进入on_message()方法,处理消息
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值