ActiveMQ:将消息存储到python

时间:2017-03-13 17:35:46

标签: python activemq

我想将从ActiveMQ队列中获取的消息存储到字符串中,但我无法知道如何操作。我的代码如下:

import stomp
import time

class SampleListener(object):
  def on_message(self, headers, msg):
    print(msg)

conn = stomp.Connection10()

conn.set_listener('SampleListener', SampleListener())

conn.start()

conn.connect()

conn.subscribe('test2')



time.sleep(1) # secs

conn.disconnect()

1 个答案:

答案 0 :(得分:2)

在您的课程中,您只有 打印 您收到的消息,您需要:

  • 将消息存储在列表中
  • 实例化类" SampleListener"并返回列表

请参阅下面代码的补充内容。

import stomp
import time

class SampleListener(object):

  #define your empty list used to store the messages
  def __init__(self):
    self.message_list = []

  def on_message(self, headers, msg):

    # appends new msg to message_list
    self.message_list.append((headers, msg))

    # comment this out if you dont want to print all msgs to console
    print(msg) 

conn = stomp.Connection10()

# instantiate the class
listener = SampleListener()

conn.set_listener('SampleListener', listener)

conn.start()

conn.connect()

conn.subscribe('test2')



time.sleep(1) # secs

conn.disconnect()

# messages received during the 1 second period stored in a list called "myMessages"
myMessages = listener.message_list