spring boot + rabbitMq整合之持久化

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,那么是否被删除,逻辑上说不可以的,因为某个时间后如果还需要使用呢?删除的风险是非常大的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值