【RabbitMQ】TTL、死信队列、延迟队列

1、TTL(Time to Live)

TTL:队列里的消息过期时间。当消息到了设置的过期时间还没被消费,就会被清除。
设置TTL的参数是 x-message-ttl,它是以Map的形式存储的。
(1)Spring设置TTL
在spring配置里,声明队列的时候同时声明此队列中消息的过期时间。

<rabbit:queue id="spring_direct_queue_ttl" name="spring_direct_queue_ttl" auto-declare="true">
	<rabbit:queue-arguments>
		<entry key="x-message-ttl" value="100000" value-type="java.lang.Integer"/>
	</rabbit:queue-arguments>
</rabbit:queue>

(2)SpringBoot设置ttl
在配置类中声明队列时通过 withArguments 绑定消息过期时间参数

@Bean
public Queue directQueueInsert(){
   
	return QueueBuilder.durable(DIRECT_QUEUE_INSERT).withArgument("x-message-ttl",100000).build();
}

(3)原生
用Map存储ttl参数,key为x-message-ttl,value为过期时间,并在声明队列时传入。

Map<String,Object> ttl = new HashMap<>();
ttl.put("x-message-ttl",100000);
channel.queueDeclare(DIRECT_QUEUE_INSERT,true,false,false,ttl);

以上方法设置了ttl时间为100s,过时不消费就会被清除。
这种在声明队列时设置消息过期时间的方式会把队列中所有的消息都设置为100s过期。如果想对队列中的某条消息设置单独过期时间,可以在发送消息前设置,方法如下:

MessagePostProcessor mpp = new MessagePostProcessor() {
   
	@Override
	public Message postProcessMessage(Message message) throws AmqpException {
   
		message.getMessageProperties().setExpiration("10000");
		return message;
	}
};
rabbitTemplate.convertAndSend(
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值