• 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()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32

    接收消息

    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
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
  • 相关阅读:
    iframe之间传递数据笔记
    为hade增加model自动生成功能
    深度学习数据集—细胞、微生物、显微图像数据集大合集
    【黑马程序员JVM学习笔记】02.内存结构
    Spring创建、Bean对象的存储和读取
    Linux中断系统
    element 封装弹窗
    单目标应用:求解旅行商问题(TSP)的猎豹优化算法(The Cheetah Optimizer,CO)提供MATLAB代码
    div内文字水平居中+垂直居中
    jstat和jmap打印堆栈排查内存泄漏
  • 原文地址:https://blog.csdn.net/weixin_42219511/article/details/136675725