码迷,mamicode.com
首页 > 编程语言 > 详细

RabbitMQ发送消息+python

时间:2016-10-21 13:09:33      阅读:306      评论:0      收藏:0      [点我收藏+]

标签:name   one   blocking   host   alpha   发送消息   测试数据   exchange   参考   

接口使用两个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

标签:name   one   blocking   host   alpha   发送消息   测试数据   exchange   参考   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!