Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stomp.py return message from listener

Tags:

python

stomp

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.

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.

Any help, hugely appreciated!

like image 334
robrant Avatar asked Feb 22 '23 10:02

robrant


2 Answers

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()

Hope that helps!!

like image 87
Buchi Avatar answered Mar 03 '23 14:03

Buchi


All you have to do, is a slight change of the listener class:

class MyListener(object):
    msg_list = []

    def __init__(self):
        self.msg_list = []

    def on_error(self, headers, message):
        self.msg_list.append('(ERROR) ' + message)

    def on_message(self, headers, message):
        self.msg_list.append(message)

And in the code, where u use stomp.py:

conn = stomp.Connection()
lst = MyListener()
conn.set_listener('', lst)
conn.start()
conn.connect()
conn.subscribe(destination='/queue/test', id=1, ack='auto')
time.sleep(2)
messages = lst.msg_list
conn.disconnect()
return render(request, 'template.html', {'messages': messages})

Stomp.py how to return message from listener - a link to stackoverflow similar question

like image 40
Tosh Avatar answered Mar 03 '23 16:03

Tosh