阅读量:1
发送JSON数据
通过调用rabbitmq.send_json(channel, user, queue=result)
能够更简单的实现发送JSON数据。
生产者
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()