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

yipeiwu_com6年前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等多个消息类型。

以上这篇python 发送和接收ActiveMQ消息的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python闭包之返回函数的函数用法示例

Python闭包之返回函数的函数用法示例

闭包(closure)不是什么可怕的东西。如果用对了地方,它们其实可以很强大。闭包就是由其他函数动态生成并返回的函数,通俗地讲,在一个函数的内部,还有一个“内层”的函数,这个“内层”的函...

Python中print和return的作用及区别解析

print只是为了向用户显示一个字符串,表示计算机内部正在发生的事情。计算机却无法使用该print出现的内容。 return是函数的返回值。该值通常是人类用户看不到的,但是计算机可以在其...

Python画图实现同一结点多个柱状图的示例

Python画图实现同一结点多个柱状图的示例

如下所示: import numpy as np x = [1,2] #横坐标 y = [3,4] #第一个纵坐标 y1 = [5,6] #第二个纵坐标 x = np.aran...

详解Python中的format格式化函数的使用方法

详解Python中的format格式化函数的使用方法

format函数实现字符串格式化的功能 基本语法为: 通过 : 和 {} 来控制字符串的操作 一、对字符串进行操作 1. 不设置指定位置,按默认顺序插入 ①当参数个数等于{}个数的时候...

Python获取邮件地址的方法

本文实例讲述了Python获取邮件地址的方法。分享给大家供大家参考。具体实现方法如下: import email.Utils   def getCleanMailAddress(st...