Updated on 2023-07-20 GMT+08:00

Message Persistence

Scenario

By default, messages produced by RabbitMQ producers are stored in the memory. When a node breaks down or restarts, how can we ensure that messages are not lost? In RabbitMQ, you can configure persistence for exchanges, queues, and messages. Persistence means writing messages in the memory to the disk to prevent them from being lost due to exceptions. However, if message persistence is enabled, RabbitMQ performance deteriorates because read and write operations are much slower in disks than in memory. Different from the lazy queue mechanism, a persisted message is stored in both the disk and memory. It is deleted from the memory only when the memory is insufficient.

  • Non-persistent queues and exchanges are lost after a restart.
  • Non-persistent messages are lost after a restart. (Messages that are sent to persistent queues or exchanges will not automatically become persistent.)
  • A message will be lost if the server restarts before the message persistence is complete.

Configuring Exchange Persistence

When creating an exchange on the RabbitMQ management UI, set durable to true, as shown in Figure 1. Figure 2 shows a successful configuration.

Figure 1 Configuring exchange persistence
Figure 2 Exchange persistence configured

Configuring Queue Persistence

When creating a queue on the RabbitMQ management UI, set durable to true, as shown in Figure 3. Figure 4 shows a successful configuration.

Figure 3 Configuring queue persistence
Figure 4 Queue persistence configured

Configuring Message Persistence

After configuring queue persistence, set MessageProperties to PERSISTENT_TEXT_PLAIN to send persistent messages to the queue.

The following example shows how to configure message persistence on a Java client.

import com.rabbitmq.client.MessageProperties;
channel.basicPublish("", "my_queue",MessageProperties.PERSISTENT_TEXT_PLAIN, message.getBytes());