Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set per message TTL with RabbitTemplate?

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);
   }
like image 232
Khoda Avatar asked Dec 05 '25 08:12

Khoda


2 Answers

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;
    }
}
like image 126
ByeBye Avatar answered Dec 06 '25 20:12

ByeBye


rabbitTemplate.convertAndSend(RabbitMqConfig.EXCHANGE,
                    RabbitMqConfig.RK,
                    String.valueOf(body),
                    message -> {
              message.getMessageProperties().setExpiration(String.valueOf(1000));
                        return message;
                    });
like image 26
impactCn Avatar answered Dec 06 '25 22:12

impactCn