RabbitMQ发送消息+python
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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:[email protected]:5672/talaris‘))
else:
connection = pika.BlockingConnection(pika.URLParameters(
‘amqp://talaris:[email protected]:5672/clair‘))
elif str(env.__name__) == ‘Alpha‘:
if msg_type is None:
connection = pika.BlockingConnection(pika.URLParameters(
‘amqp://talaris:[email protected]:5672/talaris‘))
else:
connection = pika.BlockingConnection(pika.URLParameters(
‘amqp://talaris:[email protected]: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的主要内容,如果未能解决你的问题,请参考以下文章