StartOutboxPoller 接受 ctx 并改为阻塞函数,调用方负责放进自己的 goroutine。 轮询等待由 waitOrDone 实现。ctx 取消后立即返回 false,不再 sleep 满一秒。单条发布的超时派生自该 ctx,停机时不会挂在一条消息上。 StartConsumer 同样去掉内部 go,改为阻塞到 ctx 取消。 测试覆盖 waitOrDone 的两条路径:取消后立即返回,未取消时等满间隔。
154 lines
4.6 KiB
Go
154 lines
4.6 KiB
Go
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"
|
||
"fmt"
|
||
"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
|
||
|
||
const (
|
||
// outboxPollInterval 是空批次后的等待时间。
|
||
outboxPollInterval = time.Second
|
||
// outboxBatchSize 是单轮最多投递的行数。
|
||
outboxBatchSize = 100
|
||
)
|
||
|
||
// StartOutboxPoller 轮询 outbox 表并把待投递消息发布到 timeline exchange,
|
||
// 阻塞到 ctx 取消;调用方负责把它放进自己的 goroutine。
|
||
//
|
||
// 它跑在 Worker 进程而不是 API 进程:随 API 实例数复制会让同一行被投递多次,
|
||
// 而 API 的退出路径也不该等待一个数据库轮询器。
|
||
func StartOutboxPoller(ctx context.Context, db *gorm.DB, tmq *rabbitmq.TimelineMQ) {
|
||
if db == nil || tmq == nil {
|
||
log.Printf("Outbox poller disabled: timeline mq is not initialized")
|
||
return
|
||
}
|
||
|
||
for ctx.Err() == nil {
|
||
var messages []video.OutboxMsg
|
||
|
||
err := db.Where("status = ?", "pending").Order("create_time ASC").Limit(outboxBatchSize).Find(&messages).Error
|
||
if err != nil {
|
||
log.Printf("outbox 轮询失败: %v", err)
|
||
if !waitOrDone(ctx, outboxPollInterval) {
|
||
return
|
||
}
|
||
continue
|
||
}
|
||
if len(messages) == 0 {
|
||
if !waitOrDone(ctx, outboxPollInterval) {
|
||
return
|
||
}
|
||
continue
|
||
}
|
||
|
||
for _, msg := range messages {
|
||
// 超时派生自 poller 的 ctx:进程退出时不再为一条消息多等 5 秒。
|
||
pubCtx, cancel := context.WithTimeout(ctx, outboxPublishTimeout)
|
||
err := tmq.PublishVideo(pubCtx, msg.VideoID, msg.CreateTime)
|
||
cancel()
|
||
|
||
if err == nil {
|
||
if err := db.Delete(&msg).Error; err != nil {
|
||
log.Printf("删除 outbox 消息失败: id=%d, err=%v", msg.ID, err)
|
||
}
|
||
} else {
|
||
log.Printf("投递MQ失败: VideoID: %d, err: %v", msg.VideoID, err)
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
// waitOrDone 等待 d 或 ctx 取消;返回 true 表示等满间隔,false 表示被取消。
|
||
//
|
||
// 抽成独立函数是为了让"轮询间隔可被退出信号打断"能被单测直接验证——它不碰数据库。
|
||
func waitOrDone(ctx context.Context, d time.Duration) bool {
|
||
t := time.NewTimer(d)
|
||
defer t.Stop()
|
||
select {
|
||
case <-t.C:
|
||
return true
|
||
case <-ctx.Done():
|
||
return false
|
||
}
|
||
}
|
||
|
||
// StartConsumer 消费 timeline 事件并写入 Redis ZSet,阻塞到 ctx 取消;
|
||
// 调用方负责把它放进自己的 goroutine。
|
||
//
|
||
// 连接级重连、拓扑重放、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
|
||
}
|
||
if redisClient == nil {
|
||
log.Printf("Timeline consumer disabled: redis is not initialized")
|
||
return
|
||
}
|
||
|
||
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)
|
||
}
|