小工具知识网

当前位置: 首页 > 行业知识 > python使用rabbitmq发送消息和接收消息数据

行业知识

python使用rabbitmq发送消息和接收消息数据

2026-12-04 01:08:00 来源:互联网转载

发送消息

import pika# 设置RabbitMQ连接参数(更改账号密码)credentials = pika.PlainCredentials('username', 'password')# 更改为自己的服务器地址parameters = pika.ConnectionParameters('192.168.0.157', 5672, '/', credentials)# 建立到RabbitMQ的连接connection = pika.BlockingConnection(parameters)channel = connection.channel()# 声明队列,确保它存在queue_name = 'radarQueue'  # 队列名字channel.queue_declare(queue=queue_name, durable=True, passive=True)# 要发送的消息crawled_data = {'key': 'value00'}# 将字典转换为JSON字符串crawled_data_json = json.dumps(crawled_data)# 发布消息到指定队列channel.basic_publish(exchange='',                      routing_key=queue_name,                      body=crawled_data_json.encode("utf-8"),  # 要传字节                       properties=pika.BasicProperties(                          delivery_mode=2,  # 使消息持久化                      ))print(crawled_data)# 关闭连接connection.close()

接收消息

import pika# 设置RabbitMQ连接参数credentials = pika.PlainCredentials('username', 'password')parameters = pika.ConnectionParameters('192.168.0.157', 5672, '/', credentials)# 建立到RabbitMQ的连接connection = pika.BlockingConnection(parameters)channel = connection.channel()# 声明队列,确保它存在queue_name = 'radarQueue'channel.queue_declare(queue=queue_name, durable=True, passive=True)# 定义一个回调函数,用来处理队列中的消息def callback(ch, method, properties, body):    print(f" [x] Received {body}")# 告诉RabbitMQ从队列中接收消息channel.basic_consume(queue=queue_name, on_message_callback=callback, auto_ack=True)print(' [*] Waiting for messages. To exit press CTRL+C')try:    # 开始接收消息,这会一直运行直到被中断    channel.start_consuming()except KeyboardInterrupt:    channel.stop_consuming()# 关闭连接connection.close()
()()

上一篇:个人版权申请宝典,轻松掌握流程,创意权益无忧保护!

下一篇:饥荒怎么多人联机服务器?