Redis implements delay queue

1. What is a delay queue?

Delay queue is a special type of message queue, which allows messages to be sent to the queue, but not delivered to consumers immediately, but delivered to consumers after a certain period of time.

2. Usage scenarios of delay queue

Common usage scenarios for delay queues are as follows:

Place an order on Taobao, JD.com and other shopping platforms, and if the payment is not made within a certain period of time, the order will be automatically cancelled;

When taking a taxi, if there is no car owner to accept the order within the specified time, the platform will cancel your order and remind you that there is no car owner to accept the order for the time being;

When ordering takeaway, if the merchant has not received the order within 10 minutes, the order will be automatically canceled;

The specific implementation method:

1. Use the ZADD command to add the message to the sorted set, and use the current time as the score

2. Start a consumer thread and use the zrangebyscore command to get all the messages before the current time from Zset at regular intervals

3. After consumers have processed the messages, they can delete them from the sorted set

There is a problem:

1. There is a time interval for polling, so the actual consumption time of delayed messages will be longer than the set time

2. A large number of polling will put pressure on the redis server, so it is necessary to use delayed messages. Many MQ components support this capability

It should be noted that in a multi-process or multi-machine environment, in order to ensure that each task is only executed once, you can use Redis's distributed locks to guarantee. In addition, for tasks that time out or fail, they can also be moved to another sorted set for subsequent processing.

Guess you like

Origin blog.csdn.net/miachen520/article/details/130207407