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后消息并没有马上被移除,但该消息已经不会被消费了,当它到达队列顶端时会被移除。

相关推荐
测试人社区-千羽13 小时前
智能测试的终极形态:从自动化到自主化的范式变革
运维·人工智能·python·opencv·测试工具·自动化·开源软件
锐学AI13 小时前
从零开始学MCP(八)- 构建一个MCP server
人工智能·python
木棉知行者13 小时前
PyTorch 核心方法:state_dict ()、parameters () 参数打印与应用
人工智能·pytorch·python
xingzhemengyou113 小时前
python time的使用
python
码界奇点13 小时前
基于Python与GitHub Actions的正方教务成绩自动推送系统设计与实现
开发语言·python·车载系统·自动化·毕业设计·github·源代码管理
E_ICEBLUE14 小时前
PDF vs PDF/A:区别、场景与常用转换方法(2025 全面解读)
python·pdf
岁月宁静14 小时前
🐍 Python 核心知识点:从零开始快速构建 Python 知识体系
python
阿杰同学15 小时前
Hadoop 面试题及答案整理,最新面试题
大数据·hadoop·分布式
C嘎嘎嵌入式开发15 小时前
deepseek-r1大模型的本地部署
人工智能·python·神经网络·机器学习
柯南二号15 小时前
【大前端】【Android】用 Python 脚本模拟点击 Android APP —— 全面技术指南
android·前端·python