消息队列 / 系统课时
延迟队列设计
延迟队列设计
订单超时关闭、预约提醒等任务需要“现在写入,未来处理”。RabbitMQ 可以把 TTL 与死信路由组合成无需定时扫描业务表的延迟队列:消息先等待到期,再自动转入真正的消费队列。
学习目标
- 理解 TTL 与死信交换机组合形成延迟队列的机制
- 搭建一个固定 30 秒延迟的可运行队列
- 识别多种延迟时长和重复消费场景中的设计边界
延迟不是让消费者睡眠
延迟队列的关键是把“等待”和“业务处理”拆开。生产者先把消息写入没有业务消费者的等待队列;等待队列设置 TTL,并把 DLX 指向业务交换机。消息到期后成为死信,再由 RabbitMQ 路由到真正的处理队列。
这种设计不会占用消费者线程等待,也避免应用进程重启导致内存定时器丢失。对于固定延迟,例如统一 30 分钟关闭未支付订单,队列级 TTL 是最容易验证和治理的方案。

搭建固定延迟队列
下面示例使用 30 秒队列级 TTL。orders.delay 不应启动业务消费者;消息到期后通过 DLX orders.events 和路由键 orders.timeout 进入真正的 orders.timeout 队列。
import json
import time
import pika
connection = pika.BlockingConnection(
pika.ConnectionParameters(host="localhost")
)
channel = connection.channel()
channel.exchange_declare("delay.x", exchange_type="direct", durable=True)
channel.exchange_declare("orders.events", exchange_type="direct", durable=True)
channel.queue_declare(
"orders.delay",
durable=True,
arguments={
"x-message-ttl": 30000,
"x-dead-letter-exchange": "orders.events",
"x-dead-letter-routing-key": "orders.timeout",
},
)
channel.queue_declare("orders.timeout", durable=True)
channel.queue_bind("orders.delay", "delay.x", routing_key="orders.delay")
channel.queue_bind(
"orders.timeout",
"orders.events",
routing_key="orders.timeout",
)
channel.basic_publish(
exchange="delay.x",
routing_key="orders.delay",
body=json.dumps({"orderId": 1001}),
properties=pika.BasicProperties(delivery_mode=2),
)
started = time.time()
print("published")
method = None
body = None
deadline = time.time() + 40
while time.time() < deadline:
method, _, body = channel.basic_get("orders.timeout", auto_ack=True)
if method is not None:
break
time.sleep(0.2)
if body is None:
raise RuntimeError("40 秒内未收到超时消息")
print(body.decode())
print(f"delay_seconds={int(time.time() - started)}")
connection.close()预期输出
published
{"orderId": 1001}
delay_seconds=<TIME><TIME> 应接近 30 秒,但调度、网络和队列处理会带来少量偏差,因此不要把它当作毫秒级定时器。
为不同延迟时长选择结构
如果业务只有少量固定档位,例如 5 分钟、30 分钟、2 小时,可以为每个档位建立独立等待队列,并让它们最终死信到同一个业务交换机。这样 TTL 规则固定,监控也直观。
如果在同一个队列中大量使用不同的每消息 TTL,较短延迟的消息可能受到队列前方消息影响,实际到达业务队列的时间不再容易推断。需要大量任意延迟时长时,应评估专门的延迟消息方案或外部调度系统,而不是无限增加 TTL 队列。
订单超时处理必须幂等
消息到达 orders.timeout 只代表“现在应该检查订单是否需要关闭”,并不代表订单一定仍未支付。消费者应再次读取订单当前状态,只有状态仍满足超时条件时才执行关闭;如果支付已完成,就直接确认消息而不做关闭。
当延迟消息可能重复投递时,应以订单 ID 或业务事件 ID 作为幂等键,并让“检查状态后更新”成为原子条件操作。这样即使消息重试或重复到达,也不会把已支付订单误关闭。