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.

Go to the full post