RabbitMQ's persistence mechanism includes queue persistence, message persistence, and exchange persistence. Whether the message is persistent or not, it can be written to disk.
Persistent messages are written to both disk and memory (to speed up reading), while non-persistent messages are written to disk when memory is insufficient (they will be lost after RabbitMQ restarts).
RabbitMQ Queue Persistence
When declaring a queue, you can set whether the queue needs to be persisted. In Golang, the queue is declared as follows:
q, err := ch.QueueDeclare(
"hello", // queue name
true, // whether the queue should be persisted
false,
false,
false,
nil,
)
Tip: Similar to other programming languages, the queue can be set when declaring it.
RabbitMQ Exchange Persistence
When declaring an exchange, you can set whether it needs to be persisted using properties. In Golang, it is declared as follows:
err = ch.ExchangeDeclare(
"tizi365", // exchange name
"fanout", // exchange type
true, // whether it should be persisted
false,
false,
false,
nil,
)
Tip: Similar to other programming languages, persistence can be set when declaring the exchange.
RabbitMQ Message Persistence
When publishing a message, you can set whether the message needs to be persisted through message properties.
Tip: Queue persistence does not mean the message is automatically persistent.
In Golang, messages are published as follows:
err = ch.Publish(
"tizi365", // exchange
"", // routing key
false,
false,
amqp.Publishing{
DeliveryMode:2, // message delivery mode, 1 for non-persistent, 2 for persistent
ContentType: "text/plain",
Body: []byte(body),
})