发送JSON数据
通过调用rabbitmq.send_json(channel, user, queue=result)
能够更简单的实现发送JSON数据。文章来源地址https://www.toymoban.com/news/detail-792116.html
生产者
import json
import rabbitmq
# 建立连接
connection = rabbitmq.get_connection()
# 创建管道
channel = connection.channel()
# 创建队列
queue_name = "user_manager"
result = channel.queue_declare(queue=queue_name)
# 向队列中写入数据
data = [
{"id": 1, "name": "张三", "age": 23},
{"id": 2, "name": "李四", "age": 24},
{"id": 3, "name": "王五", "age": 35},
]
for user in data:
rabbitmq.send_json(channel, user, queue=result)
# 关闭连接
connection.close()
消费者
import json
import rabbitmq
# 创建连接
connection = rabbitmq.get_connection()
# 创建管道
channel = connection.channel()
# 创建队列
queue_name = "user_manager"
channel.queue_declare(queue=queue_name, durable=False)
def callback(ch, method, properties, body):
# 解析队列中的每一条数据
ch.basic_ack(delivery_tag=method.delivery_tag)
data = body.decode("utf8")
print(json.loads(data))
# 告诉rabbitmq,用callback来接收消息
channel.basic_consume(queue_name, callback)
# 开始接收信息,并进入阻塞状态,队列里有信息才会调用callback进行处理
try:
channel.start_consuming()
finally:
connection.close()
文章来源:https://www.toymoban.com/news/detail-792116.html
到了这里,关于使用Python向RabbitMQ发送JSON数据只需要一个send_json方法的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!