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()
相关推荐
花果山总钻风12 分钟前
SQLAlchemy 中的 func 函数使用指南
python
知识中的海王26 分钟前
Python html 库用法详解
开发语言·python
面朝大海,春不暖,花不开42 分钟前
使用 Python 正则表达式实现文本替换与电话号码规范化
python·mysql·正则表达式
淘小白_TXB219643 分钟前
Python网页自动化Selenium中文文档
python·selenium·自动化·网页自动化
Clair-Sean1 小时前
【JavaSE】多线程基础学习笔记
笔记·python·学习
EverBule2 小时前
Python 训练 day46
开发语言·python
WangY_ZQ3 小时前
Python 如何在Python 3.6上安装PIP
linux·python·pip
聚客AI3 小时前
系统掌握PyTorch:图解张量、Autograd、DataLoader、nn.Module与实战模型
人工智能·pytorch·python·rnn·神经网络·机器学习·自然语言处理
狮子也疯狂3 小时前
基于Python的气象数据分析及可视化研究
python·信息可视化·数据分析
蓝婷儿4 小时前
6个月Python学习计划 Day 18 - 项目实战 · 学生成绩管理系统(OOP版)
开发语言·python·学习