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()
相关推荐
IVEN_4 小时前
只会Python皮毛?深入理解这几点,轻松进阶全栈开发
python·全栈
Ray Liang5 小时前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
AI攻城狮6 小时前
如何给 AI Agent 做"断舍离":OpenClaw Session 自动清理实践
python
千寻girling6 小时前
一份不可多得的 《 Python 》语言教程
人工智能·后端·python
AI攻城狮9 小时前
用 Playwright 实现博客一键发布到稀土掘金
python·自动化运维
曲幽9 小时前
FastAPI分布式系统实战:拆解分布式系统中常见问题及解决方案
redis·python·fastapi·web·httpx·lock·asyncio
孟健1 天前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞1 天前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
用户8307196840821 天前
RabbitMQ vs RocketMQ 事务大对决:一个在“裸奔”,一个在“开挂”?
后端·rabbitmq·rocketmq