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:
@@ -3,6 +3,7 @@ package worker
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"feedsystem_video_go/internal/middleware/rabbitmq"
|
||||
rediscache "feedsystem_video_go/internal/middleware/redis"
|
||||
"feedsystem_video_go/internal/video"
|
||||
@@ -10,10 +11,16 @@ import (
|
||||
"log"
|
||||
"time"
|
||||
|
||||
amqp "github.com/rabbitmq/amqp091-go"
|
||||
oredis "github.com/redis/go-redis/v9"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// outboxPublishTimeout 限制单条 outbox 消息的发布时间。
|
||||
// 连接管理器在断连期间会阻塞等待重连,这里加超时可以保持"失败即进入下一轮轮询"
|
||||
// 的既有语义,而不是把整个轮询器挂在一条消息上。
|
||||
const outboxPublishTimeout = 5 * time.Second
|
||||
|
||||
// 轮询器,轮询数据库中的 outbox 表,获取待投递的消息,投递到 MQ 中
|
||||
func StartOutboxPoller(db *gorm.DB, tmq *rabbitmq.TimelineMQ) {
|
||||
if db == nil || tmq == nil {
|
||||
@@ -33,7 +40,9 @@ func StartOutboxPoller(db *gorm.DB, tmq *rabbitmq.TimelineMQ) {
|
||||
}
|
||||
|
||||
for _, msg := range messages {
|
||||
err := tmq.PublishVideo(context.Background(), msg.VideoID, msg.CreateTime)
|
||||
pubCtx, cancel := context.WithTimeout(context.Background(), outboxPublishTimeout)
|
||||
err := tmq.PublishVideo(pubCtx, msg.VideoID, msg.CreateTime)
|
||||
cancel()
|
||||
|
||||
if err == nil {
|
||||
if err := db.Delete(&msg).Error; err != nil {
|
||||
@@ -47,9 +56,12 @@ func StartOutboxPoller(db *gorm.DB, tmq *rabbitmq.TimelineMQ) {
|
||||
}()
|
||||
}
|
||||
|
||||
// 消费者,消费 MQ 中的消息,写入 Redis 的 Zset 中
|
||||
func StartConsumer(tmq *rabbitmq.TimelineMQ, queueName string, redisClient *rediscache.Client, rmq *rabbitmq.RabbitMQ) {
|
||||
if tmq == nil || rmq == nil || rmq.Conn == nil {
|
||||
// StartConsumer 消费 timeline 事件并写入 Redis ZSet。
|
||||
//
|
||||
// 连接级重连、拓扑重放、channel 重建全部交给连接管理器(rabbitmq.RunConsumer),
|
||||
// 这里只关心"一条消息应该怎么被处理"。
|
||||
func StartConsumer(ctx context.Context, rmq *rabbitmq.RabbitMQ, queueName string, redisClient *rediscache.Client) {
|
||||
if rmq == nil {
|
||||
log.Printf("Timeline consumer disabled: rabbitmq is not initialized")
|
||||
return
|
||||
}
|
||||
@@ -58,66 +70,51 @@ func StartConsumer(tmq *rabbitmq.TimelineMQ, queueName string, redisClient *redi
|
||||
return
|
||||
}
|
||||
|
||||
go func() {
|
||||
for {
|
||||
// 每次重连创建独立的 Channel,不与发布者共用
|
||||
ch, err := rmq.NewChannel()
|
||||
if err != nil {
|
||||
log.Printf("Timeline consumer: 创建 Channel 失败: %v, 5秒后重试", err)
|
||||
time.Sleep(5 * time.Second)
|
||||
continue
|
||||
}
|
||||
|
||||
// 设置当前 Channel 的 QoS(Quality of Service)参数,控制消息的预取数量和大小
|
||||
// prefetch count = 10 一次最多取10个消息, prefetch size = 0 不限制预取的字节大小, global = false Qos 设置只对当前 Channel 生效
|
||||
if err := ch.Qos(10, 0, false); err != nil {
|
||||
log.Printf("Timeline consumer: QoS 设置失败: %v", err)
|
||||
}
|
||||
|
||||
msgs, err := ch.Consume(queueName, "", false, false, false, false, nil)
|
||||
if err != nil {
|
||||
log.Printf("Timeline consumer: 注册消费失败: %v, 5秒后重试", err)
|
||||
ch.Close()
|
||||
time.Sleep(5 * time.Second)
|
||||
continue
|
||||
}
|
||||
|
||||
log.Printf("Timeline consumer 已启动, queue=%s", queueName)
|
||||
|
||||
for msg := range msgs {
|
||||
var event rabbitmq.TimelineEvent
|
||||
if err := json.Unmarshal(msg.Body, &event); err != nil {
|
||||
log.Printf("Timeline consumer: 反序列化失败: %v", err)
|
||||
msg.Ack(false)
|
||||
continue
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)
|
||||
timelineKey := redisClient.Key("feed:global_timeline")
|
||||
err = redisClient.ZAdd(ctx, timelineKey, oredis.Z{
|
||||
Score: float64(event.CreateTime),
|
||||
Member: fmt.Sprintf("%d", event.VideoID),
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
log.Printf("Timeline consumer: 写入Zset失败: %v", err)
|
||||
msg.Nack(false, true)
|
||||
cancel()
|
||||
continue
|
||||
}
|
||||
|
||||
if err := redisClient.ZRemRangeByRank(ctx, timelineKey, 0, -1001); err != nil {
|
||||
log.Printf("Timeline consumer: ZRem失败: %v", err)
|
||||
}
|
||||
|
||||
msg.Ack(false)
|
||||
cancel()
|
||||
}
|
||||
|
||||
// msgs channel 关闭说明 AMQP Channel 断开,关闭并重连
|
||||
ch.Close()
|
||||
log.Printf("Timeline consumer: Channel 断开, 5秒后重连...")
|
||||
time.Sleep(5 * time.Second)
|
||||
go rabbitmq.RunConsumer(ctx, rmq, "TimelineConsumer", 10, func(ch *amqp.Channel) error {
|
||||
msgs, err := ch.Consume(queueName, "", false, false, false, false, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case msg, ok := <-msgs:
|
||||
if !ok {
|
||||
return errors.New("deliveries channel closed")
|
||||
}
|
||||
handleTimelineMessage(ctx, redisClient, msg)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// handleTimelineMessage 把一条 timeline 事件写入 Redis ZSet(幂等:member 为 VideoID)。
|
||||
func handleTimelineMessage(ctx context.Context, redisClient *rediscache.Client, msg amqp.Delivery) {
|
||||
var event rabbitmq.TimelineEvent
|
||||
if err := json.Unmarshal(msg.Body, &event); err != nil {
|
||||
log.Printf("Timeline consumer: 反序列化失败: %v", err)
|
||||
_ = msg.Ack(false)
|
||||
return
|
||||
}
|
||||
|
||||
opCtx, cancel := context.WithTimeout(ctx, 500*time.Millisecond)
|
||||
defer cancel()
|
||||
|
||||
timelineKey := redisClient.Key("feed:global_timeline")
|
||||
err := redisClient.ZAdd(opCtx, timelineKey, oredis.Z{
|
||||
Score: float64(event.CreateTime),
|
||||
Member: fmt.Sprintf("%d", event.VideoID),
|
||||
})
|
||||
if err != nil {
|
||||
log.Printf("Timeline consumer: 写入Zset失败: %v", err)
|
||||
_ = msg.Nack(false, true)
|
||||
return
|
||||
}
|
||||
|
||||
if err := redisClient.ZRemRangeByRank(opCtx, timelineKey, 0, -1001); err != nil {
|
||||
log.Printf("Timeline consumer: ZRem失败: %v", err)
|
||||
}
|
||||
|
||||
_ = msg.Ack(false)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user