rabbitmq消息持久化,避免异常情况下,消息会丢失

1) 使用python包amqp

from amqp.basic_message import Message
from amqp.connection import Connection
exchange_name = "pythontest"
msg = "this is a amqp test msg"
conn = Connection(host=host, userid=username, password=password, heartbeat=60)
channel_id = random.randint(1, conn.channel_max)
ch = conn.channel(channel_id)
ch.exchange_declare(exchange_name, 'topic', durable=True, auto_delete=False )
ch.basic_publish(Message(msg,delivery_mode=2), exchange=exchange_name)
print "succ"

注意需要设置 delivery_mode=2 

2) 使用pika包

channel.basic_publish(exchange='', routing_key='task_queue', body=message, 
                                    properties=pika.BasicProperties( delivery_mode= 2 ))
 ### delivery_mode= 2 

3) 使用Java

AMQP.BasicProperties defaultProp = new AMQP.BasicProperties.Builder().deliveryMode(2).contentType("application/json").contentEncoding("utf-8").build();

注意deliveryMode(2)

Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
// queueDeclare参数说明
// 1:queuename
// 2:durable 是否持久化
// 3:exclusive
// 4:autoDelete 是否自动删除
// 5:arguments
channel.queueDeclare(QUEUE_NAME,true,false,false,null);
channel.exchangeDeclare("javatest", "topic",true);
channel.basicPublish("",QUEUE_NAME,defaultProp,message.getBytes() ); // defaultProp注意使用.
channel.close();
connection.close();

 

备注:在queueDeclare的时候需要设置为持久化.

在发送消息的时候,需要设置deliveryMode(2) 

转载于:https://my.oschina.net/u/1538135/blog/826561

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值