RabbitMQ TTL
参考:(17条消息) RabbitMQ高级特性-TTL队列/消息_听雪楼-CSDN博客_rabbitmq ttl
以下是基于spring cloud 2.1.4+rabbitmq-server-3.8.22的实现代码
TTL(Time to live存活时间)标识消息过期时间:消费如果在存活时间到的时候还未被消费就会被自动清理
- 针对 某一个队列设置过期时间
- 针对 某个特定的 消息本身 设置过期时间(一定是从队列头开始删)
新建一个配置类对象,测试队列存活时间
package com.example.config;
import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/*
* 测试队列过期时间
*
* */
@Configuration
public class TtlConfig {
//创建交换机
@Bean
public DirectExchange directExchange7(){
return new DirectExchange("exchange_test7");
}
//创建队列
@Bean
public Queue queue7(){
//return new Queue("queue_test6");
//给队列设置一个存活时间
return QueueBuilder.durable("queue_test7")
//设置参数名和值。 参数名是x-message-ttl 表示设置消息所在队列的过期时间
.withArgument("x-message-ttl",10000)
.build();
}
//创建绑定
@Bean
public Binding binding7(){
return BindingBuilder.bind(queue7()).to(directExchange7()).with("test7.insert");
}
}
发送消息
package com.example.controller;
import com.example.confirm.MyConfirmCallBack;
import com.example.confirm.MyReturnCallBack;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/testsend")
public class TestSendController {
@Autowired
private RabbitTemplate rabbitTemplate;
@Autowired
//或者用这个
//private MyConfirmCallBack myConfirmCallBack;
private RabbitTemplate.ConfirmCallback confirmCallback;
@Autowired
//private MyReturnCallBack myReturnCallBack;
//或者用这个
private RabbitTemplate.ReturnCallback returnsCallback;
@GetMapping ("/send1")
public String send1(){
//设置confirm回调函数
rabbitTemplate.setConfirmCallback(confirmCallback);
//设置return回调函数
rabbitTemplate.setReturnCallback(returnsCallback);
//发送消息
//rabbitTemplate.convertAndSend("exchange_test6","test6.insert","消息本身");
//测试一个错误,把交换机改正确,routingKey写错
//rabbitTemplate.convertAndSend("exchange_test6","test6.insertxxx","消息本身");
//测试削峰配置是否生效,把所有东西都改正确
rabbitTemplate.convertAndSend("exchange_test6","test6.insert","消息本身");
return "ok";
}
//测试队列过期时间,发送消息
@GetMapping ("/send2")
public String send2(){
//设置confirm回调函数
rabbitTemplate.setConfirmCallback(confirmCallback);
//设置return回调函数
rabbitTemplate.setReturnCallback(returnsCallback);
//发送消息
rabbitTemplate.convertAndSend("exchange_test7","test7.insert","消息本身");
return "ok";
}
}
启动启动类,发现如下图

过10秒发现队列的消息都没了


浙公网安备 33010602011771号