欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

python 发送和接收ActiveMQ消息的实例

时间:2021-03-12 09:55:50|栏目:Python代码|点击:

ActiveMQ是java开发的消息中间件服务。可以支持多种协议(AMQP,MQTT,OpenWire,Stomp),默认的是OpenWire。而python与ActiveMQ的通信使用的是Stomp协议。而如果你的服务没有开启则需要配置开启。

首先需要安装python的stomp库。

命令如下:

pip install stomp.py

接着,就是上代码了具体如下:

# -*-coding:utf-8-*-
import stomp
import time
 
 
queue_name = '/queue/SampleQueue'
topic_name = '/topic/SampleTopic'
listener_name = 'SampleListener'
 
class SampleListener(object):
  def on_message(self, headers, message):
    print 'headers: %s' % headers
    print 'message: %s' % message
 
# 推送到队列queue
def send_to_queue(msg):
  conn = stomp.Connection10([('127.0.0.1',61613)])
  conn.start()
  conn.connect()
  conn.send(queue_name, msg)
  conn.disconnect()
 
#推送到主题
def send_to_topic(msg):
  conn = stomp.Connection10([('127.0.0.1',61613)])
  conn.start()
  conn.connect()
  conn.send(topic_name, msg)
  conn.disconnect()
 
##从队列接收消息
def receive_from_queue():
  conn = stomp.Connection10([('127.0.0.1',61613)])
  conn.set_listener(listener_name, SampleListener())
  conn.start()
  conn.connect()
  conn.subscribe(queue_name)
  time.sleep(1) # secs
  conn.disconnect()
 
##从主题接收消息
def receive_from_topic():
  conn = stomp.Connection10([('127.0.0.1',61613)])
  conn.set_listener(listener_name, SampleListener())
  conn.start()
  conn.connect()
  conn.subscribe(topic_name)
  while 1:
    send_to_topic('topic')
    time.sleep(3) # secs
 
  conn.disconnect()
 
if __name__=='__main__':
  # send_to_queue('len 123')
  # receive_from_queue()
 
  receive_from_topic()

但是上述只是发送文本类型的消息,除此之外,ActiveMQ还支持MapMessage、ObjectMessage、BytesMessage、和StreamMessage等多个消息类型。

上一篇:Restful_framework视图组件代码实例解析

栏    目:Python代码

下一篇:Python日期的加减等操作的示例

本文标题:python 发送和接收ActiveMQ消息的实例

本文地址:http://www.codeinn.net/misctech/79370.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有