Files
VLoop/backend/internal/middleware/rabbitmq/dlx.go
huanghaosheng 5f250fa7cd fix(mq): GetRetryCount 只统计 rejected,并兼容非 int64 计数
原实现取 deaths[0] 并把 count 断言成 int64,在真实链路上两条都会让结果恒为 0:

- deaths[0] 常常是重试队列的 "expired" 条目(TTL 到期),它表示"延迟结束",
  不是"处理失败";把它算进来也会让计数含义失真。
- amqp091-go 在不同路径上给出的 count 宽度不同(int32/int64/float64),
  断言 int64 失败就静默返回 0。

计数恒为 0 的后果不是"少重试几次",而是"重试永远不耗尽"——任何依赖它的
重试上限判定都会失效。改为遍历所有 x-death 条目、只累加 reason=="rejected",
并用 intField 统一宽度。

守护测试 TestGetRetryCount_CountsOnlyRejected 覆盖 7 种 x-death 形状,
含"rejected 与 expired 混合时只累加 rejected"与"多条 rejected 累加"。
2026-10-30 13:12:05 +08:00

91 lines
2.1 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package rabbitmq
import (
"log"
amqp "github.com/rabbitmq/amqp091-go"
)
const (
DLXExchange = "dlx.events"
MaxRetryCount = 3
)
// DeclareDLX 声明死信交换机和对应的死信队列(保留原有签名)。
func DeclareDLX(ch *amqp.Channel, queueName string) error {
if ch == nil {
return nil
}
return declareDLX(ch, queueName)
}
// declareDLX 是 DeclareDLX 的接口版本,供拓扑重放路径复用。
func declareDLX(d declarer, queueName string) error {
if d == nil {
return nil
}
if err := d.ExchangeDeclare(
DLXExchange, "topic", true, false, false, false, nil,
); err != nil {
return err
}
dlxQueue := queueName + ".dlx"
_, err := d.QueueDeclare(
dlxQueue, true, false, false, false, nil, // 死信队列不设置 DLX
)
if err != nil {
return err
}
if err := d.QueueBind(dlxQueue, "#", DLXExchange, false, nil); err != nil {
return err
}
log.Printf("DLX ready: exchange=%s queue=%s", DLXExchange, dlxQueue)
return nil
}
// GetRetryCount 返回这条消息被【拒绝过】的次数。
//
// 两个坑:
// 1. 不读 deaths[0]。真实链路里最新一条往往是重试队列的 "expired"(TTL 到期),
// 那是"延迟结束",不是"处理失败"。只数 reason == "rejected"。
// 2. 不假定 count 是 int64。amqp091-go 在不同路径上会给出 int32/int64/float64,
// 断言成 int64 会在真实消息上静默返回 0——计数恒为 0 就意味着"永远不重试耗尽"。
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
}
}