2 rabbitmq消息持久化

如果当rabbitmq意外宕机时,可能有持久化保存队列的需求,即队列中的消息不消失

生产者

import pika
import time

connection = pika.BlockingConnection(pika.ConnectionParameters(
    'localhost'))
channel = connection.channel()

# 声明queue,队列持久化
channel.queue_declare(queue='durable',durable=True)

# n RabbitMQ a message can never be sent directly to the queue, it always needs to go through an exchange.
channel.basic_publish(exchange='',
                      routing_key='durable',
                      body='Hello cheng!',
                      properties=pika.BasicProperties(
                          delivery_mode=2,  # make message persistent
                      )
                      )
print(" [x] Sent 'Hello cheng!'")
connection.close()
View Code

注意:队列设置为持久化,消息也必须设置持久化

消费者

import pika, time

connection = pika.BlockingConnection(pika.ConnectionParameters(
    'localhost'))
channel = connection.channel()

channel.queue_declare(queue='durable',durable=True)

def callback(ch, method, properties, body):
    print(" [x] Received %r" % body)
    time.sleep(10)
    print("11111111111111")
    #这句话放在那里,就表示给服务器回应,消息已经收到,可以从服务器的队列中删除
    ch.basic_ack(delivery_tag=method.delivery_tag)


channel.basic_consume(callback,
                      queue='durable',
                      #no_ack=True
                      )

print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()
View Code

 

posted @ 2018-05-23 00:23  会开车的好厨师  阅读(76)  评论(0)    收藏  举报