RabbitMQ(高级特性)设置单条消息存活时间

设置单条消息存活时间

java 复制代码
@Test
public void testSendMessage() {
  //设置消息属性
  MessageProperties messageProperties = new MessageProperties();
  //设置存活时间
  messageProperties.setExpiration("10000");
  // 创建消息对象
  Message message = new Message("send message...".getBytes(StandardCharsets.UTF_8), messageProperties);
  // 发送消息
  rabbitTemplate.convertAndSend("my_topic_exchange", "my_routing", message);
}

注意:

1 如果设置了单条消息的存活时间,也设置了队列的存活时间,以时间短的为准。

2 消息过期后,并不会马上移除消息,只有消息消费到队列顶端时,才会移除该消息。

第二条测试:

java 复制代码
@Test
public void testSendMessage2() {
  for (int i = 0; i < 10; i++) {
    if (i == 5) {
      // 1.创建消息属性
      MessageProperties messageProperties = new MessageProperties();
      // 2.设置存活时间
      messageProperties.setExpiration("10000");
      // 3.创建消息对象
      Message message = new Message(("send message..." + i).getBytes(), messageProperties);
      // 4.发送消息
      rabbitTemplate.convertAndSend("my_topic_exchange", "my_routing", message);
     } else {
      rabbitTemplate.convertAndSend("my_topic_exchange", "my_routing", "send message..." + i);
     }
   }
}

在以上案例中,i=5的消息才有过期时间,10s后消息并没有马上被移除,但该消息已经不会被消费了,当它到达队列顶端时会被移除。

相关推荐
哈里谢顿1 天前
Python 高并发服务限流终极方案:从原理到生产落地(2026 实战指南)
python
用户8356290780512 天前
无需 Office:Python 批量转换 PPT 为图片
后端·python
markfeng82 天前
Python+Django+H5+MySQL项目搭建
python·django
GinoWi2 天前
Chapter 2 - Python中的变量和简单的数据类型
python
JordanHaidee2 天前
Python 中 `if x:` 到底在判断什么?
后端·python
ServBay2 天前
10分钟彻底终结冗长代码,Python f-string 让你重获编程自由
后端·python
闲云一鹤2 天前
Python 入门(二)- 使用 FastAPI 快速生成后端 API 接口
python·fastapi
初次攀爬者2 天前
ZooKeeper 实现分布式锁的两种方式
分布式·后端·zookeeper
Rockbean2 天前
用40行代码搭建自己的无服务器OCR
服务器·python·deepseek
曲幽2 天前
FastAPI + Ollama 实战:搭一个能查天气的AI助手
python·ai·lora·torch·fastapi·web·model·ollama·weatherapi