This is the 22nd day of my participation in Gwen Challenge

Accumulate over a long period, constant dripping wears away a stone 😄

preface

TTL (Time To Live) : indicates the expiration Time. You can set TTL for messages and queues respectively in RabbitMQ.

Set TTL for messages

There are two ways to set the TTL of messages in RabbitMQ:

  • By setting the queue property, all messages in the queue have the same expiration time.

  • The message itself can be set separately, and the TTL for each message can be different. Note: If both methods are used together, the TTL of the message takes the smaller value in between. Once the TTL value is exceeded, the Message becomes a “Dead Message” and consumers cannot receive the Message

    Note: If the queue has a dead letter queue, the message is forwarded to the dead letter queue and can be consumed normally. We’ll talk about dead letter queues later.

Set by queue properties

Add the x-message-TTL parameter in milliseconds to channel.queueDeclare. The native API

// Get the connection object
Connection conn = RabbitMQUtil.createConn();
// Get the connection channel
Channel channel = conn.createChannel();
Map<String,Object> map = new HashMap<>();
map.put("x-message-ttl".10000);
channel.queueDeclare("ttl-quequ".true.false.true,map);
Copy the code

SpringBoot

  @Bean
    public Queue payQueue(a){
        Map<String,Object> params = new HashMap<>();
        // Set the queue expiration time
        params.put("x-message-ttl".10000);
        // You can also use the following notation
        //QueueBuilder.durable("ttl-quequ").ttl(10000).build();
        return QueueBuilder.durable("ttl-quequ").withArguments(params).build();
    }
Copy the code

If the TTL is not set, the message will not expire. If the TTL is set to 0, the message will be discarded immediately unless it can be delivered directly to the consumer.

Set to the message itself

Add the expiration parameter in milliseconds to channel.basicPublish.

The native API

// Get the connection object
Connection conn = RabbitMQUtil.createConn();
// Get the connection channel
Channel channel = conn.createChannel();
// Set the TTL for the message
channel.queueDeclare("ttl-quequ2".true.false.true.null);

channel.basicPublish(""."ttl-quequ2".new AMQP.BasicProperties().builder()
                     .expiration("30000")
                     .build(),
                     "Set message expiration time".getBytes());
Copy the code

SpringBoot

 MessagePostProcessor messagePostProcessor = message -> {
        MessageProperties messageProperties = message.getMessageProperties();
            // Set the information expiration time
            messageProperties.setExpiration("30000");
            return message;
        };
        rabbitTemplate.convertAndSend("exchangeName"."routingKey"."Message content",messagePostProcessor);
Copy the code

In the first method, the TTL attribute of the queue is set so that once the message expires, it is erased from the queue, whereas in the second method, even if the message expires, it is not immediately erased from the queue, because each message is determined before it is delivered to the consumer.

Why are these two approaches handled differently? In the first way, expired messages are always in the queue header (fifO), and RabbitMQ can periodically scan the queue header for expired messages. In the second method, the expiration time of each message can be different (the first message is set to 10s, the second message is set to 2s). If you want to delete all expired messages, you will have to scan the entire queue. Therefore, it is better to wait until the message is about to be consumed to determine whether it is expired or not.

Set TTL for the queue

The x-Expires parameter in the channel.queueDeclare method controls how long a queue is unused before it is automatically deleted. Unused means there are no consumers on the queue and the queue has not been redeclared. Even if a consumer is connected, the queue expiration time is recalculated if the consumer consumes all the messages.

RabbitMQ will ensure that the queue is deleted when it expires, but not in a timely manner. After RabbitMQ restarts, the expiration time of the persistent queue will be recalculated.

The X-Expires parameter is measured in milliseconds and subject to the same constraints as x-message-TTL, but cannot be set to 0. For example, if this parameter is set to 1000, the queue will be deleted if it is not used within one second.

The native API

public static void main(String[] args) throws IOException {
    // Get the connection object
    Connection conn = RabbitMQUtil.createConn();
    // Get the connection channel
    Channel channel = conn.createChannel();

    Map<String, Object> map = new HashMap<>();
    map.put ("x-expires" , 30000);
    // Set the TTL for the queue
    // Create a queue with an expiration time of 30 seconds
    channel.queueDeclare("ttl-quequ3".true.false.true,map);
}
Copy the code

SpringBoot

@Bean
public Queue payQueue(a){
    Map<String,Object> params = new HashMap<>();
    // Set the queue expiration time
    params.put("x-expires".10000);
    // You can also use the following notation
    //return QueueBuilder.durable(queueName).expires(5000).build();
    return QueueBuilder.durable(queueName).withArguments(params).build();
}
Copy the code

  • If you have any questions or errors in this article, please feel free to comment. If you find this article helpful, please like it and follow it.

reference

Teacher Zhu Zhonghua RabbitMQ combat Guide book.