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

发送消息

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()

相关推荐

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

    2024-03-14 10:14:01       46 阅读
  2. 如何使用 RabbitMQ 进行消息发送接收

    2024-03-14 10:14:01       45 阅读
  3. RabbitMQ保证消息被成功发送消费

    2024-03-14 10:14:01       27 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-03-14 10:14:01       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-03-14 10:14:01       100 阅读
  3. 在Django里面运行非项目文件

    2024-03-14 10:14:01       82 阅读
  4. Python语言-面向对象

    2024-03-14 10:14:01       91 阅读

热门阅读

  1. 【Leetcode】top 100 矩阵

    2024-03-14 10:14:01       44 阅读
  2. Vuex和Pinia

    2024-03-14 10:14:01       41 阅读
  3. 虚拟环境创建笔记

    2024-03-14 10:14:01       37 阅读
  4. 面试经典-9-跳跃游戏

    2024-03-14 10:14:01       41 阅读
  5. 【C++】每日一题 146 LRU缓存

    2024-03-14 10:14:01       41 阅读
  6. 无线业务配置建议

    2024-03-14 10:14:01       43 阅读
  7. nginx配置websocket

    2024-03-14 10:14:01       35 阅读
  8. Ribbon负载均衡

    2024-03-14 10:14:01       42 阅读