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

发送消息

python 复制代码
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()

接收消息

python 复制代码
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()
相关推荐
2601_9563198818 小时前
2026年下半年AI量化学习,分清表达开发和验证
人工智能·python
CTA量化套保18 小时前
最新AI量化效率提升,用示例拆解练习压实路径
人工智能·python
zhiSiBuYu051718 小时前
混合检索实战指南:关键词与向量的完美融合
人工智能·python·机器学习
weixin_4130632118 小时前
复现 MatchED 边缘检测模型(单张图片重复8次,训练200 epoch)
python·算法·计算机视觉·边缘检测模型
许彰午18 小时前
74_Python自动化办公之Excel操作
python·自动化·excel
用户8356290780512 天前
Python 实现 PDF 文件加密与解密方法
后端·python
用户8356290780512 天前
使用 Python 冻结与拆分 Excel 窗格教程
后端·python
你好潘先生2 天前
别再记命令了,用 yeero do 说句人话就能跑脚本,而且不烧 token
服务器·python·命令行
Agent_大师2 天前
WebSocket 行情重连成功,K线缺口不会自动消失
python
荣码2 天前
LLM结构化输出:让AI返回JSON而不是废话,我踩了4个坑
java·python