# 延迟队列

目前常见的应用软件都有消息的延迟推送的影子，应用也极为广泛，例如：

* 淘宝七天自动确认收货
* 30分钟内订单不确认的话自动取消订单

## 数据库 + 轮询

数据量少的情况下，比如公司内部会议室预订前15分钟提醒功能，可以直接使用 DB 存储所有数据，在到期时间上做索引。轮询根据到期时间作为查找条件即可。

## Redis Zset + 轮询

使用 `zadd key 到期时间 field` 命令为 `field` 设置到期时间，并轮询使用 `zrange` 命令取出到期的 `field` 处理

## Rabbit MQ

在 RabbitMQ 3.6.x 之前我们一般采用死信队列+TTL过期时间来实现延迟队列，我们这里不做过多介绍。

在 RabbitMQ 3.6.x 开始，RabbitMQ 官方提供了延迟队列的插件，可以下载放置到 RabbitMQ 根目录下的 plugins 下。

死信队列的工作方式是：

1. Client Publisher将消息投递给路由器，也就是exchange。
   1. 再由exchange将消息投递给队列，由队列生成该消息的构建时间。
   2. 到达构建时间的消息将过期，同时进入死信队列。
2. 消费者消费死信队列，便可在特定时间后才消费到。

## 时间轮 + 轮询


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://wtifs.gitbook.io/diva-notes/system-design/yan-chi-dui-lie.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
