主要有2种方式:
- 指定一条消息的过期时间。
- 给队列设置消息过期时间,队列中的所有消息都有同样的过期时间。
1、指定消息的过期时间
@RestController
public class TTLController {
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @PostMapping("/testTTL")
    public String testTTL() {
        MessageProperties messageProperties = new MessageProperties();
        messageProperties.setExpiration("20000"); // 设置过期时间,单位:毫秒
        byte[] msgBytes = "测试消息自动过期".getBytes();
        Message message = new Message(msgBytes, messageProperties);
        rabbitTemplate.convertAndSend("TTL_EXCHANGE", "TTL", message);
        return "ok";
    }
}
消息推送到队列后,如果指定时间内没有被消费,则会自动过期。
注意:
RabbitMQ只会对队列头部的消息进行过期淘汰。如果单独给消息设置TTL,先入队列的消息过期时间如果设置比较长,后入队列的设置时间比较短。会造成消息不会及时地过期淘汰,导致消息的堆积。
2、给队列中的所有消息设置过期时间
@Configuration
public class TTLQueueRabbitConfig {
    @Bean
    public Queue TTLQueue() {
        Map<String, Object> map = new HashMap<>();
        map.put("x-message-ttl", 30000); // 队列中的消息未被消费则30秒后过期
        return new Queue("TTL_QUEUE", true, false, false, map);
    }
    @Bean
    public DirectExchange TTLExchange() {
        return new DirectExchange("TTL_EXCHANGE", true, false);
    }
    @Bean
    public Binding bindingDirect() {
        return BindingBuilder.bind(TTLQueue()).to(TTLExchange()).with("TTL");
    }
}
声明队列时设置1个x-message-ttl的属性,并设置过期时间,凡是推送到该队列中的所有消息,都会有一个30秒后过期的属性。
可以看到创建的队列有TTL的特性,表示该队列中的消息会自动过期。

如果同时指定了Message TTL和Queue TTL,则优先较小的那一个。
RabbitMQ原生API实现消息自动过期








