业务队列的 DLX 从共享的 dlx.events 改为 retry.events.<queue>。 消息被拒绝后进入 <queue>.retry,TTL 到期经默认交换机精确回源。 因此重试消息不会跨队列回源。 重试交换机先于业务队列声明。队列被拒绝时若找不到 DLX,broker 会丢弃消息。 删掉每队列的 <queue>.dlx。它们以通配绑定同一个共享交换机,同一条死信会被扇出多份。 拓扑去重改按交换机、队列、绑定键三元组。RetryDelay 不参与比较。 因此同一队列的两种延迟不会产生两次不等价声明。 验证:go test -count=1 ./... 全绿
423 lines
15 KiB
Go
423 lines
15 KiB
Go
package rabbitmq
|
||
|
||
import (
|
||
"context"
|
||
"encoding/json"
|
||
"errors"
|
||
"fmt"
|
||
"log"
|
||
"strings"
|
||
"time"
|
||
|
||
amqp "github.com/rabbitmq/amqp091-go"
|
||
)
|
||
|
||
const (
|
||
// DLXExchange 是停泊专用交换机(复用改造前就存在的那个名字)。
|
||
DLXExchange = "dlx.events"
|
||
// ParkedQueue 是唯一的停泊队列:项目里所有"处理不了"的消息最终都落到这里,
|
||
// 由 FailedEventWorker 落库到 failed_events。
|
||
ParkedQueue = "failed.events"
|
||
// ParkedKeyPrefix 后接源队列名,构成停泊路由键 parked.<queue>。
|
||
// 源队列由路由键带回,因此一条停泊消息能自证"我从哪来"。
|
||
ParkedKeyPrefix = "parked."
|
||
// RetryExchangePrefix 让每个业务队列有独立的重试入口。
|
||
// 不能共用:like.events 与 notification.like 共享同一个业务交换机且路由键重叠,
|
||
// 共用重试exchange 无法区分来源,会把消息重投到错误的队列。
|
||
RetryExchangePrefix = "retry.events."
|
||
// RetryQueueSuffix 让每个业务队列有独立的重试队列(TTL 到期后精确回源)。
|
||
RetryQueueSuffix = ".retry"
|
||
|
||
// MaxRetryCount 与既有行为保持一致:首次投递 + 3 次重试 = 4 次尝试。
|
||
MaxRetryCount = 3
|
||
|
||
// HeaderSourceQueue 记录消息来自哪个队列。
|
||
HeaderSourceQueue = "x-vloop-source-queue"
|
||
// HeaderAttempts 记录停泊时已经用掉的尝试次数。
|
||
HeaderAttempts = "x-vloop-attempts"
|
||
// HeaderLastError 记录最后一次处理失败的原因(截断到 512 字节)。
|
||
HeaderLastError = "x-vloop-last-error"
|
||
|
||
// parkTimeout 是"停泊一条消息"的硬上限:停泊是失败路径,
|
||
// 它不能因为连接半死而把消费者的处理协程无限期占住。
|
||
parkTimeout = 5 * time.Second
|
||
)
|
||
|
||
// parkRequeueBackoff 是"停泊失败后退回 requeue"之前的退避。
|
||
//
|
||
// 没有它,当 failed.events 缺失(或 dlx.events 被误删)时 Park 会快速失败:
|
||
// mandatory 的 basic.return 立刻返回,Nack(requeue=true) 立刻重投,
|
||
// 形成每秒上万次的热循环 + 日志洪泛。
|
||
//
|
||
// 是变量而不是常量:测试把它压到毫秒级,否则"退避确实发生了"这条断言
|
||
// 会让每次跑测试都多等一秒。
|
||
var parkRequeueBackoff = time.Second
|
||
|
||
// MaxAttempts 是一次投递被允许的最大尝试次数(首次 + 重试)。
|
||
const MaxAttempts = MaxRetryCount + 1
|
||
|
||
// DefaultRetryDelay 是队列级 TTL。
|
||
//
|
||
// 用常量延迟而不是指数退避:指数退避需要客户端在每次拒绝时改写 x-message-ttl
|
||
// (= 重发消息 = 又一个重复窗口),而队列级 TTL 让"重试"完全由 broker 完成,
|
||
// 进程崩溃也不丢计数。
|
||
const DefaultRetryDelay = 5 * time.Second
|
||
|
||
// RetryExchange 返回某队列专属的重试交换机名。
|
||
func RetryExchange(queue string) string { return RetryExchangePrefix + queue }
|
||
|
||
// RetryQueueName 返回某队列专属的重试队列名。
|
||
func RetryQueueName(queue string) string { return queue + RetryQueueSuffix }
|
||
|
||
// declareParking 声明停泊链路:DLX 交换机 + 唯一停泊队列 + parked.# 绑定。
|
||
//
|
||
// 幂等,每代连接都会重放(P0-2 不变式)。停泊链路只有一个队列、一次绑定,
|
||
// 因此一条死信只会产生【一份】记录。
|
||
//
|
||
// 历史:改造前每个业务队列都声明一个 <queue>.dlx,并且都以 "#" 绑定同一个
|
||
// 交换机——topic 会把同一条死信扇出成 N 份。那条链路从未被触发过,
|
||
// 因此缺陷一直没暴露。它已随重试链路一起被删除。
|
||
func declareParking(d declarer) error {
|
||
if d == nil {
|
||
return fmt.Errorf("declare park: no declarer")
|
||
}
|
||
if err := d.ExchangeDeclare(DLXExchange, "topic", true, false, false, false, nil); err != nil {
|
||
return fmt.Errorf("declare park exchange %s: %w", DLXExchange, err)
|
||
}
|
||
if _, err := d.QueueDeclare(ParkedQueue, true, false, false, false, nil); err != nil {
|
||
return fmt.Errorf("declare park queue %s: %w", ParkedQueue, err)
|
||
}
|
||
if err := d.QueueBind(ParkedQueue, ParkedKeyPrefix+"#", DLXExchange, false, nil); err != nil {
|
||
return fmt.Errorf("bind park queue %s: %w", ParkedQueue, err)
|
||
}
|
||
// 每代连接都会重放一次,这条日志也因此每代出现一次——运维用它确认
|
||
// 停泊链路在当前连接上真的存在。
|
||
log.Printf("DLX ready: exchange=%s queue=%s", DLXExchange, ParkedQueue)
|
||
return nil
|
||
}
|
||
|
||
// RetryArgs 装配业务队列。只改 DLX 指向,不设 x-dead-letter-routing-key。
|
||
//
|
||
// 不设 routing key 的效果是"第 1 次被拒绝时保留原路由键"(like.like 仍是 like.like)。
|
||
// 注意它只对第一次成立:回源那一步由 RetryQueueArgs 显式把路由键写成队列名,
|
||
// 所以从第 2 次投递起 routingKey == 队列名。任何按 routingKey 分派的消费者
|
||
// 都会因此失效——通知 worker 因此改为按队列 + body action 分派。
|
||
func RetryArgs(queue string) amqp.Table {
|
||
return amqp.Table{"x-dead-letter-exchange": RetryExchange(queue)}
|
||
}
|
||
|
||
// RetryQueueArgs 装配重试队列:队列级 TTL + 回源到默认交换机。
|
||
//
|
||
// 队列级(而不是消息级)TTL 的理由:classic queue 只在【队首】检查过期,
|
||
// 队列级 TTL 保证队首一定是最早入队的,因此不会出现"队首还没过期、
|
||
// 后面的消息已经过期"的队头阻塞。代价是延迟是个常量。
|
||
//
|
||
// x-dead-letter-exchange 显式写 "":空串就是默认交换机。
|
||
// x-dead-letter-routing-key 写队列名:默认交换机按队列名精确投递,
|
||
// 这就是"不经过业务交换机、不可能扇出"的实现。
|
||
func RetryQueueArgs(queue string, delay time.Duration) amqp.Table {
|
||
if delay <= 0 {
|
||
delay = DefaultRetryDelay
|
||
}
|
||
return amqp.Table{
|
||
"x-message-ttl": int64(delay / time.Millisecond),
|
||
"x-dead-letter-exchange": "",
|
||
"x-dead-letter-routing-key": queue,
|
||
}
|
||
}
|
||
|
||
// GetRetryCount 返回这条消息被【拒绝过】的次数。
|
||
//
|
||
// 两个坑:
|
||
// 1. 不读 deaths[0]。真实链路里最新一条往往是重试队列的 "expired"(TTL 到期),
|
||
// 那是"延迟结束",不是"处理失败"。只数 reason == "rejected"。
|
||
// 2. 不假定 count 是 int64。amqp091-go 在不同路径上会给出 int32/int64/float64。
|
||
func GetRetryCount(d amqp.Delivery) int {
|
||
deaths, ok := d.Headers["x-death"].([]interface{})
|
||
if !ok {
|
||
return 0
|
||
}
|
||
total := 0
|
||
for _, raw := range deaths {
|
||
entry, ok := raw.(amqp.Table)
|
||
if !ok {
|
||
continue
|
||
}
|
||
if reason, _ := entry["reason"].(string); reason != "rejected" {
|
||
continue
|
||
}
|
||
total += intField(entry["count"])
|
||
}
|
||
return total
|
||
}
|
||
|
||
// intField 把 AMQP table 里的整数值统一成 int(库在不同路径上给出不同宽度)。
|
||
func intField(v any) int {
|
||
switch n := v.(type) {
|
||
case int:
|
||
return n
|
||
case int32:
|
||
return int(n)
|
||
case int64:
|
||
return int(n)
|
||
case uint32:
|
||
return int(n)
|
||
case uint64:
|
||
return int(n)
|
||
case float64:
|
||
return int(n)
|
||
default:
|
||
return 0
|
||
}
|
||
}
|
||
|
||
// ParkedInfo 是一条停泊消息的自描述信息。
|
||
type ParkedInfo struct {
|
||
SourceQueue string
|
||
Attempts int
|
||
LastError string
|
||
EventID string
|
||
}
|
||
|
||
// ParseParkedInfo 从停泊消息上还原来源与失败原因。
|
||
func ParseParkedInfo(d amqp.Delivery) ParkedInfo {
|
||
info := ParkedInfo{EventID: EventIDOf(d.Body), Attempts: 1}
|
||
if d.Headers != nil {
|
||
info.SourceQueue = stringField(d.Headers[HeaderSourceQueue])
|
||
if n := intField(d.Headers[HeaderAttempts]); n > 0 {
|
||
info.Attempts = n
|
||
}
|
||
info.LastError = stringField(d.Headers[HeaderLastError])
|
||
}
|
||
if info.SourceQueue == "" {
|
||
// 兜底:从 parked.<queue> 反推。两条来源互为校验。
|
||
info.SourceQueue = sourceQueueFromParkedKey(d.RoutingKey)
|
||
}
|
||
return info
|
||
}
|
||
|
||
// EventIDOf 只解析 event_id 一个字段,避免为取一个键而反序列化整条消息。
|
||
// 解析失败返回 ""(坏消息没有意图键,落库时写 NULL)。
|
||
func EventIDOf(body []byte) string {
|
||
var probe struct {
|
||
EventID string `json:"event_id"`
|
||
}
|
||
if err := json.Unmarshal(body, &probe); err != nil {
|
||
return ""
|
||
}
|
||
return probe.EventID
|
||
}
|
||
|
||
func stringField(v any) string {
|
||
if s, ok := v.(string); ok {
|
||
return s
|
||
}
|
||
return ""
|
||
}
|
||
|
||
func sourceQueueFromParkedKey(key string) string {
|
||
return strings.TrimPrefix(key, ParkedKeyPrefix)
|
||
}
|
||
|
||
// —— 重试/停泊策略 ——
|
||
|
||
// PermanentError 标记"重试也不会成功"的失败。
|
||
//
|
||
// 典型来源:消息体不是合法 JSON、字段非法、未知的 action。
|
||
// 这类消息每重投一次就必然再失败一次,重试只是把毒消息在队列里多放 15 秒。
|
||
type PermanentError struct {
|
||
Err error
|
||
}
|
||
|
||
func (e *PermanentError) Error() string { return e.Err.Error() }
|
||
|
||
func (e *PermanentError) Unwrap() error { return e.Err }
|
||
|
||
// Permanent 把错误标记为不可重试。nil 原样返回,已标记的不重复包装。
|
||
func Permanent(err error) error {
|
||
if err == nil {
|
||
return nil
|
||
}
|
||
if IsPermanent(err) {
|
||
return err
|
||
}
|
||
return &PermanentError{Err: err}
|
||
}
|
||
|
||
// IsPermanent 判断错误是否被 Permanent 标记过(支持 errors.Is/As 链)。
|
||
func IsPermanent(err error) bool {
|
||
var p *PermanentError
|
||
return errors.As(err, &p)
|
||
}
|
||
|
||
// Disposition 是一条消息处理完之后该做什么。
|
||
type Disposition int
|
||
|
||
const (
|
||
// DispositionAck 表示处理成功:Ack,消息结束。
|
||
DispositionAck Disposition = iota
|
||
// DispositionRetry 表示可重试失败:Nack(requeue=false),交给重试队列。
|
||
DispositionRetry
|
||
// DispositionPark 表示重试预算已用尽或不可重试:落到停泊队列。
|
||
DispositionPark
|
||
)
|
||
|
||
func (d Disposition) String() string {
|
||
switch d {
|
||
case DispositionAck:
|
||
return "ack"
|
||
case DispositionRetry:
|
||
return "retry"
|
||
case DispositionPark:
|
||
return "park"
|
||
default:
|
||
return "unknown"
|
||
}
|
||
}
|
||
|
||
// Exhausted 报告这条消息的尝试次数是否已经用完。
|
||
//
|
||
// 单独抽出来是为了留一道安全网:一条被 requeue 回来的消息可能已经超过预算
|
||
// (例如上一轮停泊失败),此时无论下一个错误是什么都不该再重试。
|
||
func Exhausted(d amqp.Delivery, maxAttempts int) bool {
|
||
if maxAttempts <= 0 {
|
||
maxAttempts = MaxAttempts
|
||
}
|
||
return GetRetryCount(d)+1 >= maxAttempts
|
||
}
|
||
|
||
// Decide 是重试策略的唯一定义点:输入一次处理结果,输出该做什么。
|
||
//
|
||
// 它是纯函数,因此"第几次失败会停泊"这类问题可以完全用表驱动测试锁住,
|
||
// 而不需要连 broker。五个消费者共用这一个判断,不会再出现"五份拷贝里
|
||
// 有一份永远走不到"的情况。
|
||
func Decide(d amqp.Delivery, maxAttempts int, err error) Disposition {
|
||
if err == nil {
|
||
return DispositionAck
|
||
}
|
||
if IsPermanent(err) || Exhausted(d, maxAttempts) {
|
||
return DispositionPark
|
||
}
|
||
return DispositionRetry
|
||
}
|
||
|
||
// ConsumeLoop 是全项目唯一的消费循环。
|
||
//
|
||
// 它只做三件事:取消息、调用 process、按 Decide 的结果处置。策略(重试几次、
|
||
// 什么时候停泊)在 Decide 里,业务在 process 里,两者都不在这里。
|
||
//
|
||
// 与改造前的区别,逐条对应 P0-3 的根因:
|
||
// - 重试不再 time.Sleep:Nack 之后由重试队列的 TTL 决定延迟,
|
||
// 消费协程立刻处理下一条,队列不会被一条坏消息堵住(D3)。
|
||
// - 重试计数来自 broker 的 x-death,进程不存任何状态,重启不丢计数(D2)。
|
||
// - 预算是用尽后 Nack 到停泊队列,而不是 Ack 丢弃(D1)。
|
||
func ConsumeLoop(
|
||
ctx context.Context,
|
||
ch *amqp.Channel,
|
||
parker Parker,
|
||
queue string,
|
||
maxAttempts int,
|
||
process func(context.Context, amqp.Delivery) error,
|
||
) error {
|
||
if ch == nil {
|
||
return errors.New("consume: channel is nil")
|
||
}
|
||
if queue == "" {
|
||
return errors.New("consume: queue is empty")
|
||
}
|
||
if process == nil {
|
||
return errors.New("consume: process is nil")
|
||
}
|
||
if maxAttempts <= 0 {
|
||
maxAttempts = MaxAttempts
|
||
}
|
||
|
||
deliveries, err := ch.Consume(queue, "", false, false, false, false, nil)
|
||
if err != nil {
|
||
return fmt.Errorf("consume %s: %w", queue, err)
|
||
}
|
||
|
||
for {
|
||
select {
|
||
case <-ctx.Done():
|
||
return nil
|
||
case d, ok := <-deliveries:
|
||
if !ok {
|
||
// channel 被关闭(连接换代或队列被删):交给 RunConsumer 重建。
|
||
return nil
|
||
}
|
||
handleOne(ctx, parker, queue, maxAttempts, d, process)
|
||
}
|
||
}
|
||
}
|
||
|
||
// handleOne 处置一条消息。Ack/Nack 失败只记日志:消息要么已经离开队列,
|
||
// 要么会被 broker 重投,两种情况下再冒泡一个错误都没有额外价值。
|
||
func handleOne(
|
||
ctx context.Context,
|
||
parker Parker,
|
||
queue string,
|
||
maxAttempts int,
|
||
d amqp.Delivery,
|
||
process func(context.Context, amqp.Delivery) error,
|
||
) {
|
||
err := process(ctx, d)
|
||
attempts := GetRetryCount(d) + 1
|
||
|
||
switch Decide(d, maxAttempts, err) {
|
||
case DispositionAck:
|
||
if ackErr := d.Ack(false); ackErr != nil {
|
||
log.Printf("consume: ack 失败 queue=%s err=%v", queue, ackErr)
|
||
}
|
||
case DispositionRetry:
|
||
log.Printf("consume: 处理失败将重试 queue=%s attempts=%d/%d err=%v", queue, attempts, maxAttempts, err)
|
||
// requeue=false:让 broker 把消息交给本队列的重试交换机,
|
||
// 由重试队列的 TTL 决定延迟。requeue=true 会立刻重投,等于没有退避。
|
||
if nackErr := d.Nack(false, false); nackErr != nil {
|
||
log.Printf("consume: nack 失败 queue=%s err=%v", queue, nackErr)
|
||
}
|
||
case DispositionPark:
|
||
parkOrRequeue(ctx, parker, queue, d, attempts, err)
|
||
}
|
||
}
|
||
|
||
// parkOrRequeue 停泊一条消息,并在停泊失败时退回 requeue。
|
||
//
|
||
// 顺序不可换:先确认停泊成功,再 Ack 原消息(G6)。反过来的话,
|
||
// 停泊失败就等于"原消息被删、停泊消息没进队列",正是要修的那种静默丢失。
|
||
func parkOrRequeue(ctx context.Context, parker Parker, queue string, d amqp.Delivery, attempts int, cause error) {
|
||
if parker == nil {
|
||
// 没有 parker 的进程(未接线或测试)宁可把消息留在队列里反复重投,
|
||
// 也不能 Ack——Ack 就是丢弃。
|
||
log.Printf("consume: 无 parker,退回 requeue queue=%s attempts=%d err=%v", queue, attempts, cause)
|
||
if !sleepCtx(ctx, parkRequeueBackoff) {
|
||
return
|
||
}
|
||
if nackErr := d.Nack(false, true); nackErr != nil {
|
||
log.Printf("consume: nack 失败 queue=%s err=%v", queue, nackErr)
|
||
}
|
||
return
|
||
}
|
||
|
||
parkCtx, cancel := context.WithTimeout(ctx, parkTimeout)
|
||
defer cancel()
|
||
|
||
if err := parker.Park(parkCtx, queue, d, attempts, cause); err != nil {
|
||
log.Printf("consume: 停泊失败,退回 requeue queue=%s attempts=%d err=%v", queue, attempts, err)
|
||
// 退避后再重投:停泊链路的故障通常是"队列/交换机不存在",Park 会立刻
|
||
// 失败,不退避就是一个每秒上万次的热循环。
|
||
if !sleepCtx(ctx, parkRequeueBackoff) {
|
||
return
|
||
}
|
||
if nackErr := d.Nack(false, true); nackErr != nil {
|
||
log.Printf("consume: nack 失败 queue=%s err=%v", queue, nackErr)
|
||
}
|
||
return
|
||
}
|
||
|
||
log.Printf("consume: 已停泊 queue=%s attempts=%d last_error=%v", queue, attempts, cause)
|
||
if ackErr := d.Ack(false); ackErr != nil {
|
||
log.Printf("consume: ack 失败 queue=%s err=%v", queue, ackErr)
|
||
}
|
||
}
|