Jay
Jay

Reputation: 1039

Message persistence in RabbitMQ

I am writing a small app where i am using RabbitMQ to send/Receive a message. Everything is working ok, but i am struggling with message persistence.

I want message to remain in a Queue even in server restarts. I understand the concept of durability at exchange and Queue level and have set them to true (rather they are default as true). So when i restart my RabbitMQ server, exchange and Queue remains intact but the messages in a queue are deleted.

I am using EasyNetQ.IBus interface to send messages.

Thanks

Upvotes: 9

Views: 18064

Answers (4)

Pouria Montakhabi
Pouria Montakhabi

Reputation: 255

Add these two lines after binding queue:

var properties = model.CreateBasicProperties();
properties.Persistent = true;

Upvotes: 1

tsuryadi
tsuryadi

Reputation: 450

Have you tried to enable the Lazy Queue? "Lazy Queues - queues that move their contents to disk as early as practically possible"

It can be enabled on the Policy level (my preference) or specific queue.

Full explanation is here https://www.rabbitmq.com/lazy-queues.html

Upvotes: 0

Vladimir Shiyanov
Vladimir Shiyanov

Reputation: 1396

Using RabbitMQ.Client, you can set the delivery mode using IBasicProperties, which can be obtained using the method IModel.CreateBasicProperties().

using (IConnection conn = factory.CreateConnection())
using (IModel channel = conn.CreateModel())
{
    channel.ExchangeDeclare(exchange, ExchangeType.Direct, durable: true);
    channel.QueueDeclare(queue, durable: true, exclusive: false, autoDelete: false, arguments: null);
    channel.QueueBind(queue, exchange, routingKey, null);

    var props = channel.CreateBasicProperties();
    props.Persistent = true; // or props.DeliveryMode = 2;

    channel.BasicPublish(exchange, routingKey, props, Encoding.Default.GetBytes(message));
}

Upvotes: 10

andani
andani

Reputation: 424

To make your message persistent in RabbitMQ, you need to add MessageProperties.PERSISTENT_TEXT_PLAIN in your code.

import com.rabbitmq.client.MessageProperties;

channel.basicPublish("", "task_queue",
        MessageProperties.PERSISTENT_TEXT_PLAIN,
        message.getBytes());

Upvotes: 4

Related Questions