Python RabbitMQ消息持久化

RabbitMQ消息持久化:就是将队列中的消息永久的存放在队列中。
 
处理方案:
# 在实例化时加入durable=True来确认消息的实例化,客户端服务端都要写
channel.queue_declare(queue='hello1',durable=True)
注:只持久化了队列,并没有持久化消息。
 
# 消息持久话,在channel.basic_publish加入参数
properties = pika.BasicProperties(delivery_mode = 2,)
注:pika.BasicProperties下可以自定以参数,delivery_mode = 2是默认的。
 
 
send端 发送消息后重启rabbitmq服务
#!/usr/bin/env python
import pika

# 通过实例创建socket
connection = pika.BlockingConnection(
        pika.ConnectionParameters('localhost')
        )

# 声明一个管道/在管道内发消息
channel = connection.channel()

# 管道内,声明一个队列,queue=queue的名字
# durable=True持久话队列
channel.queue_declare(queue='hello10',durable=True)

# routing_key = queue的名字
# body = 消息内容
# properties = pika.BasicProperties 持久话参数,可在()加入定义参数
# delivery_mode =2  持久化消息
# 一个消息不能直接发送到队列,它总是需要经过一个exchange。
channel.basic_publish(exchange='',
                      routing_key='hello10',
                      body='Hello World!',
                      properties = pika.BasicProperties(
                      delivery_mode = 2,)
                      )
print(" [x] Sent 'Hello World!'")

# 关闭队列
connection.close()

 

recv端
#_*_coding:utf-8_*_
__author__ = 'Alex Li'
import pika,time

# 实例话创建socket
connection = pika.BlockingConnection(
        pika.ConnectionParameters('localhost'))

# 声明一个管道/在管道内发消息
channel = connection.channel()

# 为什么再次声明queue名字:如果消费者先运行了,没有声明queue就会报错
# 如果想要防止报错发生,就要定义queue。
#
# 管道内,声明一个队列,queue=queue的名字
# durable=True持久话队列
channel.queue_declare(queue='hello10',durable=True)

#回调函数
# ch 管道内存对象地址
# method 消息发给哪个queue
# body = 消息内容
def callback(ch, method, properties, body):
    print(" [x] Received %r" % body)
    #time.sleep(10)
    # 消息处理完后会向生产端发送确认指令
    ch.basic_ack(delivery_tag=method.delivery_tag)

# 消费消息
# callback 如果收到消息,就调用callback函数来处理消息
# queue 管道内的队列名字
# no_ack = True 这条消息出没处理完都不会给服务端发确认
channel.basic_consume(
                    callback,
                    queue='hello10',)

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

# 启动后一直运行,没有数据会等待..
channel.start_consuming()
posted @ 2018-01-15 18:44  kevin.Xiang  阅读(727)  评论(0编辑  收藏  举报