Delayed Message Sending

The delayed message sending means that when a message is sent to Apache RocketMQ, instead of delivering the message immediately, it would be delivered to the Consumer for consumption after delaying a certain period of time.

Apache RocketMQ supports a total of 18 levels of delayed delivery, the details are as follows:

delay leveldelay timedelay leveldelay time
11s106min
25s117min
310s128min
430s139min
51min1410min
62min1520min
73min1630min
84min171h
95min182h

The sample code for the delayed message sending is as follows:

  1. public class ScheduledMessageProducer {
  2. public static void main(String[] args) throws Exception {
  3. // Instantiate a producer to send scheduled messages
  4. DefaultMQProducer producer = new DefaultMQProducer("ExampleProducerGroup");
  5. // Launch producer
  6. producer.start();
  7. int totalMessagesToSend = 100;
  8. for (int i = 0; i < totalMessagesToSend; i++) {
  9. Message message = new Message("TestTopic", ("Hello scheduled message " + i).getBytes());
  10. // This message will be delivered to consumer 10 seconds later.
  11. message.setDelayTimeLevel(3);
  12. // Send the message
  13. producer.send(message);
  14. }
  15. // Shutdown producer after use.
  16. producer.shutdown();
  17. }
  18. }

Delayed Message Sending - 图1tip

The most important thing is to set the delay level for the message. In the sample code above, the delay level is set to 3, which means that after the sender sends the message, it would take 10s for the consumer to receive it.