Per-queue message time-to-live (TTL)

One of the RabbitMQ protocol extension to the AMQP specification is that we can specify the messages lifetime on a queue. This is done setting the x-message-ttl argument to a non-negative integer value, representing the time to live in milliseconds.

For instance, if we want to use a queue named "ttl", with a time to live of half a second, we could write something like this (I use Java 7, as you can deduce from the diamond operator):
public class SendRecTTL {
    private final static String QUEUE_NAME = "ttl";
    private final static int TTL = 500;
    private Map<String, Object> args = new HashMap<>();

    public SendRecTTL() { args.put("x-message-ttl", TTL); }

    // ...

        channel.queueDeclare(QUEUE_NAME, false, false, false, args);
A message sent to this queue would expire after half a second, and would be considered "dead".

I have written a simple test application for the current RabbitMQ version (2.8.2) that sends and receives a message on such a queue. Adding a sleep between the two actions, we can see what happen if the delay is too big.

Better if your code is prepared to not receive anything, not hanging forever:
QueueingConsumer.Delivery delivery = consumer.nextDelivery(1000);
if(delivery == null)
{
    // ...
Full Java source code on github.

4 comments:

  1. Replies
    1. message published to a queue no one consumed it (i am not set any ttl args) can server discarded that messages by default?

      Delete
    2. I guess I don't get your point. If you want the server to discard a message that is not consumed, you set a TTL. If you don't set it, you are stating that the server should not discard any message.

      Delete