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

相关推荐
Python大数据分析@6 分钟前
Origin、MATLAB、Python 用于科研作图,哪个最好?
开发语言·python·matlab
编程零零七34 分钟前
Python巩固训练——第一天练习题
开发语言·python·python基础·python学习·python练习题
Zonda要好好学习1 小时前
Python入门Day4
java·网络·python
暗影八度1 小时前
Spark流水线数据质量检查组件
大数据·分布式·spark
小龙在山东2 小时前
Python 包管理工具 uv
windows·python·uv
weixin_307779132 小时前
批量OCR的GitHub项目
python·github·ocr
CodeWithMe2 小时前
【Note】《Kafka: The Definitive Guide》 第5章:深入 Kafka 内部结构,理解分布式日志系统的核心奥秘
分布式·kafka
CodeWithMe3 小时前
【Note】《Kafka: The Definitive Guide》第一章:Meet Kafka
分布式·kafka
CodeWithMe3 小时前
【Note】《Kafka: The Definitive Guide》 第二章 Installing Kafka:Kafka 安装与运行
分布式·kafka
孤狼warrior3 小时前
灰色预测模型
人工智能·python·算法·数学建模