feat(video): 热度写入单轨化,点赞兜底不再重复插入

热度有两个写入者(PopularityWorker 与兜底直写)和三份实现,其中
VideoService.UpdatePopularity 是死代码且漏删 video:entity 缓存。这里
收敛成一条轨,并让"加过分"这件事可以判重。

- popularity_cache: UpdatePopularityCache 改成 5 参数并返回 error,
  用 redis SETNX 占位 hot:applied:<意图键> 实现幂等;ZINCRBY 失败必须
  撤销占位再上抛(占位留在失败路径上会让增量被永久跳过);三次 Del 是
  best-effort,不受 opCtx 约束。返回 error 同时修掉 P0-3 的 N2——
  原来三条路径全返回 nil,消费端的 Nack/重试/sleep 全是死代码。
- popularityMQ.Update / likeMQ.Like/Unlike 增加 intentKey 入参,写进
  event_id,让点赞事件与热度事件共享一次判重身份。
- like_service: 兜底拆成两个独立的 if(!likeEnqueued 写 DB、
  !popEnqueued 写热榜)。旧代码"两个都成功才 return"会在"点赞已入队 +
  热度发布失败"时再插一次 likes,撞唯一索引返回 500,而点赞其实成功了。
- 删除 VideoService.UpdatePopularity 及其 popularityMQ 字段与构造参数
  (router.go 是唯一调用点)。

行为变更:点赞在热度发布失败时不再返回 500。热度是展示数据,失败只降级
记日志,不回滚已经成立的点赞。
This commit is contained in:
2026-10-30 13:25:48 +08:00
parent d734cc9e43
commit 90a7feb6d3
9 changed files with 312 additions and 87 deletions

View File

@@ -4,26 +4,27 @@ import (
"context"
"encoding/json"
"errors"
"strconv"
"strings"
"time"
"feedsystem_video_go/internal/apierror"
"feedsystem_video_go/internal/middleware/rabbitmq"
rediscache "feedsystem_video_go/internal/middleware/redis"
"gorm.io/gorm"
)
type VideoService struct {
repo *VideoRepository
cache *rediscache.Client
cacheTTL time.Duration
popularityMQ *rabbitmq.PopularityMQ
repo *VideoRepository
cache *rediscache.Client
cacheTTL time.Duration
}
func NewVideoService(repo *VideoRepository, cache *rediscache.Client, popularityMQ *rabbitmq.PopularityMQ) *VideoService {
return &VideoService{repo: repo, cache: cache, cacheTTL: 5 * time.Minute, popularityMQ: popularityMQ}
// NewVideoService 不再接收 popularityMQ:热度写入只有两个入口——
// PopularityWorker(异步)与 LikeService/CommentService 的兜底路径,
// 视频服务从来不直接改热度。原来这里挂着一个没人调用的 UpdatePopularity,
// 它是热度写入的第三份实现,且漏删 video:entity 缓存(P0-4 的 N3)。
func NewVideoService(repo *VideoRepository, cache *rediscache.Client) *VideoService {
return &VideoService{repo: repo, cache: cache, cacheTTL: 5 * time.Minute}
}
func (vs *VideoService) Publish(ctx context.Context, video *Video) error {
@@ -199,32 +200,3 @@ func (vs *VideoService) UpdateLikesCount(ctx context.Context, id uint, likesCoun
}
return nil
}
func (vs *VideoService) UpdatePopularity(ctx context.Context, id uint, change int64) error {
if err := vs.repo.UpdatePopularity(ctx, id, change); err != nil {
return err
}
if vs.popularityMQ != nil {
if err := vs.popularityMQ.Update(ctx, id, change); err == nil {
return nil
}
}
if vs.cache != nil {
// 1) 详情缓存:直接失效(最简单靠谱)
_ = vs.cache.Del(context.Background(), vs.cache.Key("video:detail:id=%d", id))
// 2) 热榜:写到“时间窗ZSET”,不要用 detail key
now := time.Now().UTC().Truncate(time.Minute)
windowKey := vs.cache.Key("hot:video:1m:%s", now.Format("200601021504"))
member := strconv.FormatUint(uint64(id), 10)
opCtx, cancel := context.WithTimeout(ctx, 50*time.Millisecond)
defer cancel()
_ = vs.cache.ZincrBy(opCtx, windowKey, member, float64(change))
_ = vs.cache.Expire(opCtx, windowKey, 2*time.Hour)
}
return nil
}