RabbitMq 队列/消息持久化与消息(自动/手动)确认Ack

  • Mq connection 文件

import pika

host = "127.0.0.1"
port = "5672"


def mq_conn():
    credentials = pika.PlainCredentials('admin', 'admin')  # mq用户名和密码
    # 虚拟队列需要指定参数 virtual_host,如果是默认的可以不填。
    connection = pika.BlockingConnection(
        pika.ConnectionParameters(host='127.0.0.1', port=5672, virtual_host='my_vhost', credentials=credentials))
    channel = connection.channel()

    return channel
  • Mq produce(队列与消息持久化设置)

from py_rabbitmq.mq_connection import mq_conn, pika

conn = mq_conn()

# 声明队列
conn.queue_declare(queue='hello', durable=True)

for i in range(5):
    conn.basic_publish(exchange='',
                       routing_key='hello',
                       body='Hello World!',
                       properties=pika.BasicProperties(delivery_mode=2))
    print("produce is body")

conn.close()

# 队列持久化需要在声明队列时添加参数 durable=True,这样在rabbitmq崩溃时也能保存队列, 仅仅使用durable=True ,只能持久化队列,不能持久化消息

# 消息持久化需要在消息生成时,添加参数 properties=pika.BasicProperties(delivery_mode=2)


  • Mq consume(自动/手动Ack消息确认)

    from py_rabbitmq.mq_connection import mq_conn
    
    conn = mq_conn()
    
    # 声明队列
    conn.queue_declare(queue='hello', durable=True)
    
    
    def callback(ch, method, properties, body):
        print(" [x] Received %r" % body)
    
        time.sleep(15)
        # print("done")
        ch.basic_ack(delivery_tag=method.delivery_tag)
    
    
    # auto_ack=True 消息自动确认, 息被消费者接收到就应答,但是如果消费者消费消息失败,这时候会造成消息丢失 (自动Ack)
    # ch.basic_ack(delivery_tag=method.delivery_tag) 必须等消息处理完成且没发生报错,才做应答(手动Ack)
    
    conn.basic_consume(queue='hello', on_message_callback=callback)
    
    conn.start_consuming()
    

     

你可能感兴趣的:(后端,消息队列)