注释搬家到 docs/design/message-failure-handling.md。 删除复述代码的注释、历史缺陷说明与批次编号。保留的类型断言、索引语义、声明顺序等约束已在文档中展开。 重写 dlx.go、topology.go、consumer.go 三个文件,其余文件只删注释。 唯一非注释改动是 topology.go 里两处 ExchangeDeclare 由多行压成单行,语义不变。 验证:go test -count=1 ./... 全绿。
48 lines
1.4 KiB
Go
48 lines
1.4 KiB
Go
package worker
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
|
|
"feedsystem_video_go/internal/middleware/rabbitmq"
|
|
rediscache "feedsystem_video_go/internal/middleware/redis"
|
|
"feedsystem_video_go/internal/video"
|
|
|
|
amqp "github.com/rabbitmq/amqp091-go"
|
|
)
|
|
|
|
type PopularityWorker struct {
|
|
ch *amqp.Channel
|
|
parker rabbitmq.Parker
|
|
cache *rediscache.Client
|
|
queue string
|
|
}
|
|
|
|
func NewPopularityWorker(ch *amqp.Channel, parker rabbitmq.Parker, cache *rediscache.Client, queue string) *PopularityWorker {
|
|
return &PopularityWorker{ch: ch, parker: parker, cache: cache, queue: queue}
|
|
}
|
|
|
|
func (w *PopularityWorker) Run(ctx context.Context) error {
|
|
if w == nil || w.ch == nil {
|
|
return errors.New("popularity worker is not initialized")
|
|
}
|
|
if w.queue == "" {
|
|
return errors.New("queue is required")
|
|
}
|
|
return rabbitmq.ConsumeLoop(ctx, w.ch, w.parker, w.queue, rabbitmq.MaxAttempts, w.process)
|
|
}
|
|
|
|
func (w *PopularityWorker) process(ctx context.Context, d amqp.Delivery) error {
|
|
var evt rabbitmq.PopularityEvent
|
|
if err := json.Unmarshal(d.Body, &evt); err != nil {
|
|
return rabbitmq.Permanent(fmt.Errorf("popularity worker: decode event: %w", err))
|
|
}
|
|
if evt.VideoID == 0 || evt.Change == 0 {
|
|
return rabbitmq.Permanent(fmt.Errorf("popularity worker: invalid event video_id=%d change=%d", evt.VideoID, evt.Change))
|
|
}
|
|
// 必须把错误上抛,否则重试分支是死代码。
|
|
return video.UpdatePopularityCache(ctx, w.cache, evt.VideoID, evt.Change, evt.EventID)
|
|
}
|