首页 > 代码库 > RabbitMQ发送消息+python
RabbitMQ发送消息+python
接口使用两个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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。