Springboot整合RabbitMQ(四)——設定訊息過期時間TTL
阿新 • • 發佈:2020-11-12
主要有2種方式:
- 指定一條訊息的過期時間。
- 給佇列設定訊息過期時間,佇列中的所有訊息都有同樣的過期時間。
1、指定訊息的過期時間
@RestController
public class TTLController {
@Autowired
private RabbitTemplate rabbitTemplate;
@PostMapping("/testTTL")
public String testTTL() {
MessageProperties messageProperties = new MessageProperties();
messageProperties.setExpiration("20000"); // 設定過期時間,單位:毫秒
byte[] msgBytes = "測試訊息自動過期".getBytes();
Message message = new Message(msgBytes, messageProperties);
rabbitTemplate.convertAndSend("TTL_EXCHANGE", "TTL", message);
return "ok";
}
}
訊息推送到佇列後,如果指定時間內沒有被消費,則會自動過期。
注意:
RabbitMQ
只會對佇列頭部的訊息進行過期淘汰。如果單獨給訊息設定TTL,先入佇列的訊息過期時間如果設定比較長,後入佇列的設定時間比較短。會造成訊息不會及時地過期淘汰,導致訊息的堆積。
2、給佇列中的所有訊息設定過期時間
@Configuration
public class TTLQueueRabbitConfig {
@Bean
public Queue TTLQueue() {
Map<String, Object> map = new HashMap<>();
map.put("x-message-ttl", 30000); // 佇列中的訊息未被消費則30秒後過期
return new Queue("TTL_QUEUE", true, false, false, map);
}
@Bean
public DirectExchange TTLExchange() {
return new DirectExchange("TTL_EXCHANGE", true, false);
}
@Bean
public Binding bindingDirect() {
return BindingBuilder.bind(TTLQueue()).to(TTLExchange()).with("TTL");
}
}
宣告佇列時設定1個x-message-ttl
的屬性,並設定過期時間,凡是推送到該佇列中的所有訊息,都會有一個30秒後過期的屬性。
可以看到建立的佇列有TTL
的特性,表示該佇列中的訊息會自動過期。
如果同時指定了Message TTL
和Queue TTL
,則優先較小的那一個。
參考資料
程式碼地址
- github:https://github.com/senlinmu1008/spring-boot/tree/master/rabbitmq-ttl-dlx
- gitee:https://gitee.com/ppbin/spring-boot/tree/master/rabbitmq-ttl-dlx
作者:砒霜拌辣椒
連結:https://www.jianshu.com/p/341c63cf0459
來源:簡書
著作權歸作者所有。商業轉載請聯絡作者獲得授權,非商業轉載請註明出處。