我们知道,如果消息接收端挂了,消息会保存在队列里。下次接收端启动就会接收到消息。
如果RabbitMQ挂了怎么办呢?这时候需要将消息持久化到硬盘
消息发送端:producer
........... # 建立管道 channel = connection.channel() # 声明队列 1、加上durable=True进行队列持久化。两边都要加(当RabbitMQ服务down了之后) channel.queue_declare(queue="q1",durable=True) # 发消息 channel.basic_publish(exchange='', routing_key='q1', body='everything is just beginning!', # 3、加上这句话,对消息进行持久化,只需要在发送方写(RabbitMQ服务down了之后) properties=pika.BasicProperties(delivery_mode=2)) .......
消息接收端:consumer
......... # 建管道 channel = connection.channel() # 声明队列 2、加上durable=True进行队列持久化 channel.queue_declare(queue='q1', durable=True) def callback(ch, method, properties, body): print("--->:",ch,properties) time.sleep(10) print("received: ", body) ch.basic_ack(delivery_tag=method.delivery_tag) ............
这样改动,当RabbitMQ挂了之后可以对消息队列和里面的消息进行持久化。