使用python怎么实现发送和接收ActiveMQ消息

发布时间:2021-06-15 17:19:00 作者:Leah
来源:亿速云 阅读:585

使用python怎么实现发送和接收ActiveMQ消息,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

首先需要安装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()

看完上述内容,你们掌握使用python怎么实现发送和接收ActiveMQ消息的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

推荐阅读:
  1. queue和topic消息发送接收模型是什么
  2. RabbitMQ使用Python测试发送接收消息

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python activemq

上一篇:Python中怎么对ping终端进行检查

下一篇:如何理解Flask异常处理

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》