使用stomp协议,以及对应的python版本, 安装的时候使用 pip install stomp.py 安装
activemq有queue及topic两种消息类型,这里只用到queue, 同时activemq应当使用 比较新的版本
import time import os import stomp start = time.time() user = os.getenv("ACTIVEMQ_USER") or "admin" password = os.getenv("ACTIVEMQ_PASSWORD") or "admin" host = os.getenv("ACTIVEMQ_HOST") or "192.168.1.1" port = os.getenv("ACTIVEMQ_PORT") or 61613 messages = 10 conn = stomp.Connection(host_and_ports=[(host, port)]) conn.start() conn.connect(login=user, passcode=password) destination = "testmq" for i in range(0, messages): data = str(time.time()) conn.send(destination, data, persistent='false') conn.send(destination, "SHUTDOWN", persistent='false') conn.disconnect() end = time.time() timecost = end - start print "Total time cost = %s second" % timecost print "Average send speed = %s message/second" % (messages / timecost)
另一种方式, 实际上一样,但是代码较简洁:
def sendmsgtomq(message, phonenum="138xxxxxxxxx"): # 将消息发送给mq 由短信网关处理 conn = stomp.Connection([("192.168.1.1",61613)]) conn.start() conn.connect(wait=True) print "[%s]发送消息到mq, content=%s, sendto=%s"%(time.strftime("%Y-%m-%d %H:%M:%S"),message, phonenum) conn.send(body="", headers={"content":message, "phoneNo":phonenum}, destination="/queue/smsinfo") time.sleep(2) conn.disconnect()