Stomp.py 从监听器返回消息 [英] Stomp.py return message from listener

查看:31
本文介绍了Stomp.py 从监听器返回消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将 stomp.py (3.0.5) 与 python (2.6) 与 Apache ActiveMQ (5.5.1) 一起使用.我有 基本示例 工作没有任何问题,但现在我想返回将接收到的消息(在 on_message() 中)发送到 MyListener 类之外的变量.

Using stomp.py (3.0.5) with python (2.6) alongside Apache ActiveMQ (5.5.1). I have got the basic example working without any problems, but now I want to return the received message (in on_message()) to a variable outside the MyListener class.

我可以想象这是一项非常标准的任务,但我的一般 Python 技能还不够好,无法弄清楚如何去做.我已经在谷歌上搜索了一个更高级的例子并阅读了全局变量,但我似乎仍然无法将消息放入变量中,而不仅仅是将其打印到屏幕上.

I can imagine this is a pretty standard task, but my general python skills aren't good enough to work out how to do it. I've trawled google for a more advanced example and read up on global variables, but I still can't seem to get the message into a variable rather than just printing it to screen.

任何帮助,非常感谢!

推荐答案

由于监听器会在接收者线程中被调用,如果你想在其他线程(例如主线程)中处理消息,你应该做一个线程切换.

Since the listener will be called in receiver thread, you should do a thread handoff if you want to process the message in other thread (main thread, for example).

线程切换的一个简单示例是使用共享变量锁定并在接收方线程接收到消息时更新该变量.并且,在另一个线程中读取该变量,但您需要使用适当的同步机制来确保您不会覆盖该消息,并且不会遇到死锁.

One simple example of thread handoff is using a shared variable with locking and update that variable when message is received by the receiver thread. And, read that variable in the other thread but you need to use proper synchronization mechanism to make sure that you don't override the message, and you will not run into deadlocks.

这是使用一些带锁定的全局变量的示例代码.

Here is the sample code to use some global variable with locking.

rcvd_msg = None
lock = thread.Condition()

# executed in the main thread
with lock:
    while rcvd_msg == None:
        lock.wait()
    # read rcvd_msg
    rcvd_msg = None
    lock.notifyAll()

class Listener(ConnectionListener):      

    def on_message(self, headers, message):
        # executed in the receiver thread
        global rcvd_msg, lock
        with lock:
            while rcvd_msg != None:
                lock.wait()
            rcvd_msg = message
            lock.notifyAll()

希望有帮助!!

这篇关于Stomp.py 从监听器返回消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆