代码只留一行不变量。进程分工的动机、退避与重连的细节、测试可验证性的理由,都已在 docs/solutions/P1-1-async-workers-out-of-api.md 里写过,注释不再复述。 保留的是读代码看不出来的约束:超时派生自 poller 的 ctx、坏消息不能打断订阅、SSE 响应永不结束、订阅存活够久要重置退避。 文档补一句退避重置规则。这是删掉的注释里唯一没有落在文档上的细节。 验证:go test -count=1 ./... 全绿。
141 lines
3.7 KiB
Go
141 lines
3.7 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"
|
||
)
|
||
|
||
// 断连期间 Publish 会阻塞等待重连,超时让它失败并进入下一轮轮询。
|
||
const outboxPublishTimeout = 5 * time.Second
|
||
|
||
const (
|
||
// 空批次后的等待时间。
|
||
outboxPollInterval = time.Second
|
||
outboxBatchSize = 100
|
||
)
|
||
|
||
// StartOutboxPoller 阻塞轮询 outbox 表;调用方负责起 goroutine。
|
||
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 取消则提前返回 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 事件;调用方负责起 goroutine。
|
||
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)
|
||
}
|