RabbitMQ 入门指南——初步使用
MQ的消息持久化
https://www.rabbitmq.com/tutorials/tutorial-two-java.html
When RabbitMQ quits or crashes it will forget the queues and messages unless you tell it not to. Two things are required to make sure that messages aren't lost: we need to mark both the queue and messages as durable.
First, we need to make sure that RabbitMQ will never lose our queue. In order to do so, we need to declare it as durable:
首先,我们先保证MQ从不会丢弃我们的队列。为了这样,需要声明它为持久化的:
boolean durable = true;
channel.queueDeclare("task_queue", durable, false, false, null);
This queueDeclare change needs to be applied to both the producer and consumer code.
这个声明需要应用在生产者和消费者两处。
At this point we're sure that the task_queue queue won't be lost even if RabbitMQ restarts. Now we need to mark our messages as persistent - by setting MessageProperties (which implements BasicProperties) to the value PERSISTENT_TEXT_PLAIN.
我们确保任务队列即使MQ重启也不回丢失。现在,我们需要标记我们的消息为持久化的——通过设置MessageProperties
为PERSISTENT_TEXT_PLAIN
。
import com.rabbitmq.client.MessageProperties;
channel.basicPublish("", "task_queue",
MessageProperties.PERSISTENT_TEXT_PLAIN,
message.getBytes());
Note:
上面的这个方法是正确的,当在我们的例子中也无法持久化!因为已经定义的队列,再次定义是无效的,这就是幂次原理。RabbitMQ 不允许重新定义一个已有的队列信息,也就是说不允许修改已经存在的队列的参数。如果你非要这样做,只会返回异常。
咋整?
一个快速有效的方法就是重新声明另一个名称的队列,不过这需要修改生产者和消费者的代码,所以,在开发时,最好是将队列名称放到配置文件中。
这时,即使 RabbitMQ 服务器重启,新队列中的消息也不会丢失。