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

相关推荐
最晚的py几秒前
机器学习--损失函数
人工智能·python·机器学习·损失函数
free-elcmacom几秒前
机器学习入门<4>RBFN算法详解
开发语言·人工智能·python·算法·机器学习
Qinana几秒前
当AI为你写SQL,连数据库都开始谈恋爱了
人工智能·python·sql
CrazyClaz2 分钟前
分布式事务专题2
分布式·分布式事务
唐古乌梁海10 分钟前
【PyCharm】PyCharm 常用技巧与快捷键总结
ide·python·pycharm
San3016 分钟前
从 Mobile First 到 AI First:用 Python 和大模型让数据库“开口说话”
数据库·python·sqlite
AIsdhuang25 分钟前
2025 AI培训权威推荐榜:深度评测与趋势前瞻
大数据·人工智能·python
dagouaofei26 分钟前
AI制作年终总结PPT零基础可用
人工智能·python·powerpoint
卿雪27 分钟前
MySQL【存储引擎】:InnoDB、MyISAM、Memory...
java·数据库·python·sql·mysql·golang
Q_Q51100828527 分钟前
python+django/flask+vue的基于文学创作的社交论坛系统
spring boot·python·django·flask·node.js·php