python 通过stomp操作ActiveMQ

最近用到了这个,记录一下。

python通过stomp协议与ActiveMQ通信。

首先要确认下ActiveMQ是否开启了stomp服务(默认是开启的):

端口号默认为:61613

发送与接收消息:

 1 class MyListener(object):
 2 
 3     def __init__(self, conn):
 4         self.conn = conn
 5 
 6     def on_error(self, headers, message):
 7         print '$$$ received an error: %s from MQ' % message
 8 
 9     def on_message(self, headers, message):
10         print '$$$ received a message: %s from MQ' % message
11         # print headers
12         self.conn.ack(id=headers['message-id'], subscription=headers['subscription']) # 消费消息记录
13 
14         prepare_folder()
15         self.write_record(config_file, message)
16 
17 def messagequeue_invoker():
18     dest = '/queue/TestPysoider'
19     #logging.basicConfig()
20 
21     conn = stomp.Connection([('127.0.0.1', 61613)])
22     conn.set_listener('', MyListener(conn)) # 注册消息监听者
23     conn.start()
24     conn.connect(username='admin', passcode='admin', wait=True, headers={'tcpNoDelay': 'true'})
25     conn.send(destination=dest, body='I am a test message.', headers={'type': 'textMessage'}) # 发送消息
26     print "$$$ send one message"
27 
28     conn.subscribe(destination=dest, id=123, ack='client') # 开始监听接收消息
29     print 'start to receive message......'
30     while True:
31         try:
32             time.sleep(1)
33         except:
34             break

由于python各种库的版本变化较快,调用参数与方式可能有变化。之前在网上找资料就发现好多有不能执行。

可以通过查看源代码以及注释的方法校准方法调用方式(参数列表);

通过打印传入参数查看监听方法的使用以及消费消息记录的调用方式。

技巧很弱,仅作总结。

欢迎大神指教。

posted @ 2017-09-11 10:34  近海735  阅读(3583)  评论(1编辑  收藏  举报