feat(rabbitmq): 连接管理器接管连接生命周期,MQ 重启后自动恢复

原实现全进程只 amqp.Dial 一次,之后所有消费者共享该连接,而
runWorkerWithRetry 只重建 channel。amqp091-go 的连接一旦关闭,Channel()
会直接返回 ErrClosed(connection.go:842-848),连一次网络 I/O 都不会发出,
因此循环退化为"每 5 秒打一行日志"的死转:MQ 重启后 8 个消费者永久卡死,
只能人工重启进程。

本次把 RabbitMQ 从"持有一个 Conn 字段的结构体"改为连接管理器:

- 连接私有化,只由 supervise 协程创建;断连由 NotifyClose 事件驱动(必须用
  带缓冲 channel,否则会卡死库的 shutdown 路径),重连采用指数退避 + 抖动。
- 引入"连接代":Session 同时返回 channel 与其所属代的令牌,避免消费者拿着
  旧 channel 等在新代上——那会表现为永久挂起,与原始缺陷无法区分。
- 就绪判定一律以 conn 为准,ready 仅作状态变化广播,因此不存在
  "ready 与 conn 不一致"的窗口;install / markDown 在同一把锁内成对迁移状态。
- 拓扑登记(RegisterTopology)与重放(EnsureTopology)分离:每次重连后自动
  重放全部已登记拓扑,从而同时修掉报告之外的第二种卡死——"连接活着但队列
  没了"(broker 数据卷重建、队列被删、声明参数冲突),那种情况永远不会触发
  连接重连。
- 新增 consumer.go:RunConsumer 是全项目唯一的消费循环。断连期间阻塞等待
  (不轮询、不打日志,消除 96 行/分钟的 504 噪声),恢复后重建 channel、重新
  设置 QoS 并重新 Consume;channel 级异常则先重放拓扑再退避重试。原先三处
  重复实现(prefetch 还分别为 50 / 无 / 10)收敛为一处。
- 为连接注入 connection 接口,使连接代状态机可脱离 broker 被测试。

API 侧接线同步改造:outboxworker 的 StartConsumer 委托 RunConsumer,router.go
的 3 个通知消费者改用 RunConsumer(原为手写 5 秒轮询重连)。

publisher 的改造放在下一个提交;本提交先用一个带注释的临时兼容函数
PublishJSON 让尚未迁移的 5 个 publisher 继续编译,下一次提交即删除。
This commit is contained in:
2026-10-14 14:03:08 +08:00
parent 87f6e91ed1
commit 65ca5c5218
4 changed files with 805 additions and 126 deletions

View File

@@ -16,6 +16,7 @@ import (
"time"
"github.com/gin-gonic/gin"
amqp "github.com/rabbitmq/amqp091-go"
"gorm.io/gorm"
)
@@ -194,62 +195,50 @@ func SetRouter(db *gorm.DB, cache *rediscache.Client, rmq *rabbitmq.RabbitMQ) *g
protectedMessageGroup.POST("/send", messageHandler.Send)
protectedMessageGroup.POST("/list", messageHandler.List)
}
//worker
// worker:Outbox 轮询 + Timeline 消费者
// 连接级重连 / 拓扑重放 / channel 重建统一由连接管理器(rabbitmq.RunConsumer)负责
timelineMQ, err := rabbitmq.NewTimelineMQ(rmq)
if err != nil {
log.Printf("timelineMQ init failed (mq disabled): %v", err)
timelineMQ = nil
}
worker.StartOutboxPoller(db, timelineMQ)
worker.StartConsumer(timelineMQ, "video.timeline.update.queue", cache, rmq)
worker.StartConsumer(context.Background(), rmq, "video.timeline.update.queue", cache)
// SSE notification
if rmq != nil {
if notifCh, err := rmq.NewChannel(); err == nil {
if err := rabbitmq.DeclareTopic(notifCh, "like.events", "notification.like", "like.like"); err != nil {
log.Printf("notification like topic init failed: %v", err)
}
if err := rabbitmq.DeclareTopic(notifCh, "comment.events", "notification.comment", "comment.publish"); err != nil {
log.Printf("notification comment topic init failed: %v", err)
}
if err := rabbitmq.DeclareTopic(notifCh, "social.events", "notification.social", "social.follow"); err != nil {
log.Printf("notification social topic init failed: %v", err)
}
notifCh.Close()
}
}
sseHub := worker.NewSSEHub(db)
notifGroup := r.Group("/notification")
notifGroup.Use(sseHub.SSERequireAuth())
sseHub.RegisterRoutes(r, notifGroup)
go func() {
if rmq != nil {
hub := sseHub
ctx := context.Background()
// 每个 notification worker 独立 Channel + 自动重连
for _, q := range []string{"notification.like", "notification.comment", "notification.social"} {
go func(queue string) {
for {
ch, err := rmq.NewChannel()
if err != nil {
log.Printf("notification-%s: 创建 Channel 失败: %v, 5秒后重试", queue, err)
time.Sleep(5 * time.Second)
continue
}
w := worker.NewNotificationWorker(ch, db, queue, hub)
if err := w.Run(ctx); err != nil {
log.Printf("notification-%s: %v, 5秒后重连...", queue, err)
}
ch.Close()
time.Sleep(5 * time.Second)
}
}(q)
}
} else {
log.Printf("Notification SSE disabled (MQ not available)")
// 3 个 notification 消费者:拓扑登记后由管理器随每一代连接重放
if rmq != nil {
rmq.RegisterTopology(
rabbitmq.Topology{Exchange: "like.events", Queue: "notification.like", BindingKey: "like.like"},
rabbitmq.Topology{Exchange: "comment.events", Queue: "notification.comment", BindingKey: "comment.publish"},
rabbitmq.Topology{Exchange: "social.events", Queue: "notification.social", BindingKey: "social.follow"},
)
for _, q := range []string{"notification.like", "notification.comment", "notification.social"} {
queue := q
go rabbitmq.RunConsumer(context.Background(), rmq, "notification-"+queue, 10,
func(ch *amqp.Channel) error {
return worker.NewNotificationWorker(ch, db, queue, sseHub).Run(context.Background())
})
}
}()
} else {
log.Printf("Notification SSE disabled (MQ not available)")
}
// 所有 publisher / consumer 都已登记拓扑:在【当前】连接上立即声明一遍。
// 重连时管理器会自动重放,因此这里只需处理"首次连接早于拓扑登记"的启动顺序。
// 用带超时的 ctx,避免连接恰在此刻断开时把 API 启动挂住。
if rmq != nil {
initCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
if err := rmq.EnsureTopology(initCtx); err != nil {
log.Printf("rabbitmq topology init failed (will be redeclared on reconnect): %v", err)
}
cancel()
}
return r
}