首页 > 编程语言 > 详细

RabbitMQ发送消息+python

时间:2016-10-21 13:06:25      阅读:802      评论:0      收藏:0      [点我收藏+]

接口使用两个queue监听信息,且有两个测试环境,所以需要向mq中发送测试数据:

python使用pika包:Pika is a RabbitMQ (AMQP-0-9-1) client library for Python.

可以参照: https://github.com/pika/pika

import pika
connection = pika.BlockingConnection()
channel = connection.channel()
channel.basic_publish(exchange=‘example‘,
                      routing_key=‘test‘,
                      body=‘Test Message‘)
connection.close()

将发送消息封装成一个函数:stream.py

具体代码如下:

import pika
import json
from config import env


def send_msg(msg_exchange, msg_key, msg, msg_type=None):
if str(env.__name__) == ‘Beta‘:
if msg_type is None:
connection = pika.BlockingConnection(pika.URLParameters(
‘amqp://talaris:talaris@vpcb-talaris-mq-1.vm.elenet.me:5672/talaris‘))
else:
connection = pika.BlockingConnection(pika.URLParameters(
‘amqp://talaris:talaris@vpcb-talaris-mq-1.vm.elenet.me:5672/clair‘))

elif str(env.__name__) == ‘Alpha‘:
if msg_type is None:
connection = pika.BlockingConnection(pika.URLParameters(
‘amqp://talaris:talaris@vpca-talaris-mq-1.vm.elenet.me:5672/talaris‘))
else:
connection = pika.BlockingConnection(pika.URLParameters(
‘amqp://talaris:talaris@vpca-talaris-mq-1.vm.elenet.me:5672/clair‘))

channel = connection.channel()

channel.basic_publish(exchange=msg_exchange,
routing_key=msg_key,
body=json.dumps(msg))

print(" [x] Sent %r:%r" % (msg_key, msg))
connection.close()

ps: 我用的是pika.URLParameters,也可以使用 pika.ConnectionParameters(host=‘localhost‘),详细参考github

 

RabbitMQ发送消息+python

原文:http://www.cnblogs.com/sunshine2016/p/5984091.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!