I'm using spring-boot with rabbitMQ and I'm wondering if I can use per message TTL using RabbitTemplate. So far I have :
@Autowired
private RabbitTemplate rabbit;
public void produce() {
rabbit.convertAndSend("My.Queue", routingKey, message);
}
You can create MessagePostProcessor
and use it in you rabbitTemplate
:
final String message = "message";
final MessagePostProcessor messagePostProcessor = new MyMessagePostProcessor(10000);
rabbitTemplate.convertAndSend("my.queue", "routingKey", message, messagePostProcessor);
This will catch you message, apply changes and send further.
public class MyMessagePostProcessor implements MessagePostProcessor {
private final Integer ttl;
public MyMessagePostProcessor(final Integer ttl) {
this.ttl = ttl;
}
@Override
public Message postProcessMessage(final Message message) throws AmqpException {
message.getMessageProperties().getHeaders().put("expiration", ttl.toString());
return message;
}
}
Just to have a little workaround:
@Autowired
private RabbitTemplate rabbit;
@Autowired
private MessageConverter jsonMessageConverter;
public void produce() {
rabbit.setExchange("My.Exchange");
rabbit.setRoutingKey("R.K");
rabbit.setMessageConverter(jsonMessageConverter);
MessageProperties props = new MessageProperties();
props.setExpiration(Long.toString(expiration));
Message toSend = new Message(message.toString().getBytes(), props);
rabbit.send(toSend);
}
如果您要使用MessagePostProcessor
解决方案,您应该向消息添加属性而不是标题。
message.getMessageProperties().setExpiration(ttl.toString());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.