RabbitMq的持久化
什么是rabbitmq的持久化?如果rabbitmq的服务器重启的话,那么rabbitmq服务器上未消费的消息理论上是不能删除的,所以我们需要考虑这个问题,这个需要设置初始化,在spring rabbitMq中,queue的初始化如下:
/**
* The queue is durable, non-exclusive and non auto-delete.
*
* @param name the name of the queue.
*/
public Queue(String name) {
this(name, true, false, false);
}
调用的方法是:
/**
* Construct a new queue, given a name, durability, exclusive and auto-delete flags.
* @param name the name of the queue.
* @param durable true if we are declaring a durable queue (the queue will survive a server restart)
* @param exclusive true if we are declaring an exclusive queue (the queue will only be used by the declarer's
* connection)
* @param autoDelete true if the server should delete the queue when it is no longer in use
*/
public Queue(String name, boolean durable, boolean exclusive, boolean autoDelete) {
this(name, durable, exclusive, autoDelete, null);
}
durable是默认为true的,那么表示在服务器重启的时候,服务器会持久化保留该消息。
我们创建一组对照mq,默认的是durable=true(TestDirectQueue),另外一个为false(TestNotDurableDirectQueue)。代码如下:
@Bean
public Queue TestNotDurableDirectQueue(){
return new Queue("TestNotDurableDirectQueue",false);
}
@Bean
Binding bindingNotDurableDirect() {
return BindingBuilder.bind(TestNotDurableDirectQueue())
.to(TestDirectExchange())
.with("TestNotDurableDirectRouting");
}
另外分别发送mq:
@GetMapping("/send-durable-queue-and-not")
public String sendDurableQueueAndNot() {
// 发送持久化mq
Map<String, Object> durableMessage = getMqMessage();
//将消息携带绑定键值:AxCalculateUADMessage 发送到交换机AxCalculateUADMessage
rabbitTemplate.convertAndSend("TestDirectExchange",
"TestDirectRouting", durableMessage);
// 发送非持久化mq
Map<String, Object> notDurableMessage = getMqMessage();
//将消息携带绑定键值:AxCalculateUADMessage 发送到交换机AxCalculateUADMessage
rabbitTemplate.convertAndSend("TestDirectExchange",
"TestNotDurableDirectRouting", notDurableMessage);
return "ok";
}
比如,我们先发送一个mq不消费。
这里TestDirectQueue有两个是因为原先就有了一个的,请忽略
我们重启服务器,看到TestNotDurableDirectQueue 已经被删除了,那么表示队列未被持久化
RabbitMQ持久化机制这篇文章还涉及到message消息体本身是否持久化的设置,但是暂时不考虑这个问题。
另外,做个autoDelete和durable的补充,autoDelete的意思是指在某个时间段exchange或者queue被使用,比如没绑定exchange,queue或者consumer,那么是否被删除,逻辑上说不可以的,因为某个时间后如果还需要使用呢?删除的风险是非常大的。