rabbitmq消息持久化,避免異常狀況下,消息會丟失

1) 使用python包amqpjava

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 python

2) 使用pika包json

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

3) 使用Javaapp

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

注意deliveryMode(2)dom

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的時候須要設置爲持久化.ui

在發送消息的時候,須要設置deliveryMode(2) this

相關文章
相關標籤/搜索