2026-10-19 11:16:29 +08:00
<!DOCTYPE html>
< html lang = "zh-CN" data-theme = "light" >
< head >
< meta charset = "utf-8" >
< meta name = "viewport" content = "width=device-width, initial-scale=1" >
< title > 第 11 章 点赞 / 评论 / 关注:三条写路径的差异与降级 · VLoop 项目学习< / title >
< meta name = "description" content = "把三个互动模块并排比较:点赞的 MQ-first 与唯一索引幂等、评论缺失的幂等、关注反过来的 DB-first, 以及各自的降级分支与计数副作用。" >
< meta name = "keywords" content = "点赞,评论,关注,异步落库,降级,幂等,一致性" >
< link rel = "stylesheet" href = "assets/doc.css" >
< / head >
< body >
< header class = "topbar" >
< div class = "tb-in" >
< a class = "brand" href = "index.html" > < span class = "logo" > VL< / span > < div > VLoop 项目学习< small > Go + Vue 全栈 · 源码拆解 / 面试模拟 / 场景还原< / small > < / div > < / a >
< nav class = "partnav" id = "partnav" > < a class = "home" href = "index.html" > 学习地图< / a > < span class = "pn-sep" > < / span > < a href = "part-0.html" > 篇 0 前言< / a > < a href = "part-1.html" > 篇 1 知识学习< / a > < a href = "part-2.html" class = "on" > 篇 2 项目拆解< / a > < a href = "part-3.html" > 篇 3 面试模拟< / a > < a href = "part-4.html" > 篇 4 场景还原< / a > < a href = "part-5.html" > 篇 5 收尾< / a > < / nav >
< div class = "spacer" > < / div >
< button class = "btn" id = "tocToggle" > ☰ 导航< / button >
< button class = "btn" id = "themeBtn" title = "切换到深色主题" > 深色< / button >
< / div >
< / header >
< div class = "layout" id = "layout" >
< aside class = "sidebar" >
< h2 > 章节目录< / h2 >
< nav id = "chapters" > < div class = "toc-scope" > < span class = "ts-label" > 篇 2< / span > < span class = "ts-name" > 项目拆解< / span > < a class = "ts-all" href = "index.html" > 全部篇章 →< / a > < / div > < a class = "toc-a" href = "05-architecture.html" > < i class = "cn" > 5< / i > 工程结构与双进程: API 与 Worker 如何分工< / a > < a class = "toc-a" href = "06-datamodel.html" > < i class = "cn" > 6< / i > 数据模型与表关系:十张表怎么设计< / a > < a class = "toc-a" href = "07-auth.html" > < i class = "cn" > 7< / i > 账号与鉴权:双 Token、会话撤销与限流< / a > < a class = "toc-a" href = "08-video.html" > < i class = "cn" > 8< / i > 视频发布:上传、封面、话题标签与 Outbox< / a > < a class = "toc-a" href = "09-feed.html" > < i class = "cn" > 9< / i > Feed 流:三级缓存、冷热分离与游标分页< / a > < a class = "toc-a" href = "10-popularity.html" > < i class = "cn" > 10< / i > 热榜与热度:分钟窗口、快照合并与稳定分页< / a > < span class = "toc-a active" aria-current = "page" > < i class = "cn" > 11< / i > 点赞 / 评论 / 关注:三条写路径的差异与降级< / span > < div class = "subnav current" > < a class = "toc-a lv3" href = "#sec-11-1" > 11.1 点赞: MQ-first 与唯一索引幂等< / a > < a class = "toc-a lv3" href = "#sec-11-2" > 11.2 评论:同构写路径与缺失的幂等< / a > < a class = "toc-a lv3" href = "#sec-11-3" > 11.3 关注:反过来的 DB-first + MQ 仅通知< / a > < a class = "toc-a lv3" href = "#sec-11-4" > 11.4 降级矩阵: MQ 或 Redis 挂掉会发生什么< / a > < a class = "toc-a lv3" href = "#sec-11-5" > 11.5 三个 Worker 的落库逻辑与计数副作用< / a > < a class = "toc-a lv3" href = "#sec-11-6" > 11.6 提及通知:唯一绕过 MQ 的写入路径< / a > < a class = "toc-a lv3" href = "#sec-11-7" > 11.7 读不到自己的写:异步一致性的用户体验< / a > < / div > < a class = "toc-a" href = "12-mq.html" > < i class = "cn" > 12< / i > 消息队列与可靠性:连接管理器、拓扑重放与消费循环< / a > < a class = "toc-a" href = "13-chunk.html" > < i class = "cn" > 13< / i > 分片上传:会话、校验与断点续传< / a > < a class = "toc-a" href = "14-notify.html" > < i class = "cn" > 14< / i > 通知、SSE 与私信:实时推送链路< / a > < a class = "toc-a" href = "15-cache-limit.html" > < i class = "cn" > 15< / i > 缓存与限流: 键空间、TTL、分布式锁与窗口算法< / a > < a class = "toc-a" href = "16-observability.html" > < i class = "cn" > 16< / i > 可观测性与部署: 探针、pprof、Compose、start.sh 与 CI< / a > < / nav >
< div class = "side-foot" >
< a class = "btn" href = "index.html" > ← 学习地图< / a >
< a class = "btn" href = "22-cheatsheet.html" > 速查与自测< / a >
< / div >
< / aside >
< div class = "mask" id = "mask" > < / div >
< main class = "main-col" >
< article >
< p class = "chapnav" >
< a href = "index.html" > VLoop 项目学习< / a >
< span > ·< / span >
< a href = "part-2.html" > 篇 2 项目拆解< / a >
< span > ·< / span >
< span > 第 < b class = "pos" > 11< / b > / 22 章< / span >
< / p >
< h2 id = "ch11" > < span class = "n" > 11< / span > 点赞 / 评论 / 关注:三条写路径的差异与降级< / h2 >
< div class = "lead" >
2026-10-19 13:08:58 +08:00
< b > 这一章解决什么:< / b > 「点赞」「评论」「关注」看起来是同一类操作——写一条关系记录,再改一个计数。但项目里这三条路径的< b > 写入顺序是相反的< / b > :点赞和评论是「先发 MQ, MQ 失败才直写数据库」( MQ-first) , 关注却是「先写数据库, 再发 MQ, 而 MQ 只负责发通知」。本章解释这个不一致是< b > 有意取舍< / b > 还是< b > 历史遗留< / b > , 给出完整的降级矩阵, 并指出两条路径各自的代价: MQ-first 换来的是写路径与推送链路的解耦,代价是< b > 用户可能读不到自己刚写的操作< / b > 。
2026-10-19 11:16:29 +08:00
< / div >
< h3 id = "sec-11-1" > 11.1 点赞: MQ-first 与唯一索引幂等< / h3 >
2026-10-19 13:08:58 +08:00
< p > 点赞是这个项目里< b > 写路径设计最完整< / b > 的一处,因为它是唯一同时具备「异步落库」「降级直写」「数据库级幂等」三个特性的操作。先看完整的服务层入口:< / p >
< pre data-lang = "go" data-name = "backend/internal/video/like_service.go:31-60" > func (s *LikeService) Like(ctx context.Context, like *Like) error {
if like == nil {
return errors.New("like is nil")
}
if like.VideoID == 0 || like.AccountID == 0 {
return errors.New("video_id and account_id are required")
}
if s.VideoRepo != nil {
ok, err := s.VideoRepo.IsExist(ctx, like.VideoID)
if err != nil {
return err
}
if !ok {
return errors.New("video not found")
}
}
isLiked, err := s.repo.IsLiked(ctx, like.VideoID, like.AccountID)
if err != nil {
return err
}
if isLiked {
return errors.New("user has liked this video")
}
like.CreatedAt = time.Now()
mysqlEnqueued := false
redisEnqueued := false
if s.likeMQ != nil {< / pre >
< p > 前 30 行是< b > 三道前置检查< / b > ,每一道都有明确的意图,但第三道值得怀疑:< / p >
< p > < b > ① 参数非空< / b > ( < code > like is nil< / code > 、ID 非 0) ——纯防御。< / p >
< p > < b > ② 视频存在性检查< / b > ( < code > s.VideoRepo.IsExist< / code > ,返回 < code > "video not found"< / code > )。这里有个细节:< code > if s.VideoRepo != nil< / code > ——一个< b > 永真< / b > 的判断。因为 < code > LikeService< / code > 由 < code > router.go:115-117< / code > 手工装配,< code > VideoRepo< / code > 是构造时必传的参数,从来没有为 nil 的情况。这种「为可选依赖写的 nil 检查」出现在不该出现的地方,会让读者误以为这个依赖是可选的。< / p >
< p > < b > ③ 重复点赞检查< / b > ( < code > s.repo.IsLiked< / code > ,返回 < code > "user has liked this video"< / code > )。这一道是< b > 代码上写了对、思想上是多余的< / b > : < code > likes< / code > 表有联合唯一索引 < code > idx_like_video_account< / code > ( < code > like_entity.go:5-10< / code > 的 < code > uniqueIndex:idx_like_video_account< / code > ),数据库本身就不允许同一用户对同一视频产生两行点赞记录。所以这道预检查的真正价值只有「给用户一个更友好的错误信息」,而不能提供任何并发安全性——< b > 两个并发请求可能同时通过这道检查< / b > 。< / p >
< div class = "box note" >
< span class = "bt" > 「先查后写」不能做幂等,唯一约束才能< / span >
< code > IsLiked< / code > 是 < code > SELECT COUNT(*) WHERE video_id = ? AND account_id = ?< / code > ,它与后面的 < code > INSERT< / code > < b > 之间没有任何锁或事务< / b > 。所以两个并发的点赞请求可以都读到 < code > count = 0< / code > ,然后都执行 < code > INSERT< / code > ——第二次会被唯一索引拒绝( MySQL 1062) 。< br >
这正是项目采用「< b > 让数据库做最后一道防线、再把约束错误翻译成业务语义< / b > 」这条路线的原因。要正确的幂等,只有三种办法:唯一索引 + 忽略冲突、< code > INSERT … ON DUPLICATE KEY UPDATE< / code > 、或对 (video_id, account_id) 加行锁。而「先 SELECT 再 INSERT」在并发下永远是错的。< br >
顺带说:这道预检查也不是白做的。它把「重复点赞」这个< b > 常见< / b > 情况在内存里解决掉,避免了去数据库制造一次必然会失败的 INSERT。属于「性能优化」, 不是「正确性保证」。
< / div >
< p > 继续往下,就是 MQ-first 的核心——两个布尔变量与两次发布:< / p >
< pre data-lang = "go" data-name = "backend/internal/video/like_service.go:60-106( 节选) " > if s.likeMQ != nil {
if err := s.likeMQ.Like(ctx, like.AccountID, like.VideoID); err == nil {
mysqlEnqueued = true
}
}
if s.popularityMQ != nil {
if err := s.popularityMQ.Update(ctx, like.VideoID, 1); err == nil {
redisEnqueued = true
}
}
if mysqlEnqueued & & redisEnqueued {
return nil
}
// Fallback: direct MySQL write when like MQ publish fails.
if !mysqlEnqueued {
err := s.repo.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
if err := tx.Select("id").First(& Video{}, like.VideoID).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return errors.New("video not found")
}
return err
}
if err := tx.Create(like).Error; err != nil {
if isDupKey(err) {
return errors.New("user has liked this video")
}
return err
}
if err := tx.Model(& Video{}).Where("id = ?", like.VideoID).
UpdateColumn("likes_count", gorm.Expr("likes_count + 1")).Error; err != nil {
return err
}
return tx.Model(& Video{}).Where("id = ?", like.VideoID).
UpdateColumn("popularity", gorm.Expr("popularity + 1")).Error
})
if err != nil {
return err
}
}
// Fallback: direct Redis update when popularity MQ publish fails.
if !redisEnqueued {
UpdatePopularityCache(ctx, s.cache, like.VideoID, 1)
}
return nil
}< / pre >
< p > 这段结构需要理解三件事,才能看懂后面所有域的差异。< / p >
< p > < b > ① 「一个业务动作 = 两个独立的事件流」。< / b > 一次点赞实际上要向两个交换机发布两条语义完全不同的事件:< code > like.events< / code > (带上 < code > like.like< / code > 路由键)负责「数据库里的点赞关系」,< code > video.popularity.events< / code > (路由键 < code > video.popularity.update< / code > ) 负责「Redis 里的热度」。它们由两个不同的 worker 消费、写两个不同的存储,< b > 彼此之间没有任何依赖< / b > 。所以 < code > mysqlEnqueued< / code > 与 < code > redisEnqueued< / code > 必须是两个独立开关——这是全章最重要的一点,因为「任一失败就全部回退」的写法会造成重复写入。< / p >
< p > < b > ② 降级是「按目标分别发生」,不是事务回滚。< / b > 只有 < code > !mysqlEnqueued< / code > 时才开事务直写数据库;只有 < code > !redisEnqueued< / code > 时才直写 Redis。如果 MQ 那条成功了、Redis 那条失败了,代码只执行第二个 < code > if< / code > ,不会把已经进队列的点赞再写一遍。< b > 这是正确的设计< / b > ——它把「分布式事务」问题降级成了「两条各自可独立降级的分支」。< / p >
< p > < b > ③ 降级事务里的幂等靠 < code > isDupKey< / code > 。< / b > < / p >
< pre data-lang = "go" data-name = "backend/internal/video/like_service.go:26-29" > func isDupKey(err error) bool {
var me *mysql.MySQLError
return errors.As(err, & me) & & me.Number == 1062
}< / pre >
< p > 这是「把数据库约束错误翻译成业务语义」的完整实现:< code > errors.As< / code > 把错误链里的 < code > *mysql.MySQLError< / code > 取出来,比对 < code > Number == 1062< / code > ( MySQL 的 < code > ER_DUP_ENTRY< / code > )。< b > 这个技巧在本项目里被拷贝了三份< / b > ——< code > like_repo.go:37-40< / code > 的 < code > LikeIgnoreDuplicate< / code > 、< code > social/service.go< / code > 与 < code > socialworker.go:95-113< / code > (后者用 < code > errors.As< / code > 后直接判断,而不是复用 < code > isDupKey< / code > )。三份实现、零处复用,是「没有共享工具包」的典型代价。< / p >
< p > 注意 < code > Create< / code > 失败会< b > 返回错误并让整个事务回滚< / b > ,但两种 1062 的处理策略不同:< code > tx.Create(& Video{})< / code > 那条路径(视频不存在时)返回 < code > "video not found"< / code > ,而 < code > tx.Create(like)< / code > 冲突时返回 < code > "user has liked this video"< / code > 。也就是说< b > 在一个用户眼里「重复点赞」是 500 错误< / b > ——因为 handler 把所有服务层错误统一映射成 500( 见 11.4)。< / p >
< p > < code > Unlike< / code > 的骨架与 < code > Like< / code > 完全对称,但降级事务的写法不同:它< b > 不做 < code > First< / code > 存在性检查< / b > ,而是直接用 < code > RowsAffected< / code > 判断:< / p >
< pre data-lang = "go" data-name = "backend/internal/video/like_service.go:151-171( 节选) " > if !mysqlEnqueued {
err := s.repo.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
del := tx.Where("video_id = ? AND account_id = ?", like.VideoID, like.AccountID).Delete(& Like{})
if del.Error != nil {
return del.Error
}
if del.RowsAffected == 0 {
return errors.New("user has not liked this video")
}
if err := tx.Model(& Video{}).Where("id = ?", like.VideoID).
UpdateColumn("likes_count", gorm.Expr("GREATEST(likes_count - 1, 0)")).Error; err != nil {
return err
}
return tx.Model(& Video{}).Where("id = ?", like.VideoID).
UpdateColumn("popularity", gorm.Expr("GREATEST(popularity - 1, 0)")).Error
})< / pre >
< p > 删除路径用 < code > RowsAffected == 0< / code > 代替了「先查再删」——< b > 这是正确的做法< / b > ,因为 < code > DELETE< / code > 本身就会返回「删了几行」,没必要多一次 < code > SELECT< / code > 。< code > GREATEST(…, 0)< / code > 则是防止计数变成负数:即使因为某种原因(重复消费、降级与 MQ 双写)导致减多了,计数也会停在 0 而不是 -1。< b > 这是本项目里唯一主动防御「计数下溢」的地方。< / b > < / p >
2026-10-19 11:16:29 +08:00
< h3 id = "sec-11-2" > 11.2 评论:同构写路径与缺失的幂等< / h3 >
2026-10-19 13:08:58 +08:00
< p > 评论的写路径是< b > 照着点赞抄的< / b > ,结构逐行对应:参数校验 → 视频存在性 → 双发布 → 两路降级。< / p >
< pre data-lang = "go" data-name = "backend/internal/video/comment_service.go:41-91( 节选) " > exists, err := s.VideoRepository.IsExist(ctx, comment.VideoID)
if err != nil {
return err
}
if !exists {
return errors.New("video not found")
}
mysqlEnqueued := false
redisEnqueued := false
if s.commentMQ != nil {
if err := s.commentMQ.Publish(ctx, comment.Username, comment.VideoID, comment.AuthorID, comment.Content); err == nil {
mysqlEnqueued = true
}
}
if s.popularityMQ != nil {
if err := s.popularityMQ.Update(ctx, comment.VideoID, 1); err == nil {
redisEnqueued = true
}
}
if mysqlEnqueued & & redisEnqueued {
s.notifyMentions(ctx, comment)
return nil
}
// Fallback: direct MySQL write when comment MQ publish fails.
if !mysqlEnqueued {
if err := s.repo.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
if err := tx.Select("id").First(& Video{}, comment.VideoID).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return errors.New("video not found")
}
return err
}
if err := tx.Create(comment).Error; err != nil {
return err
}
return tx.Model(& Video{}).Where("id = ?", comment.VideoID).
UpdateColumn("popularity", gorm.Expr("popularity + 1")).Error
}); err != nil {
return err
}
}< / pre >
< p > 与点赞对照,有< b > 三处刻意的差异< / b > 和< b > 一处致命的缺失< / b > 。< / p >
< p > < b > 差异一:降级事务里只更新 < code > popularity< / code > ,不更新 < code > likes_count< / code > 。< / b > 这是对的——评论不会增加点赞数。点赞的降级事务同时改两列,评论的只改一列。< / p >
< p > < b > 差异二:没有「重复评论」的预检查。< / b > 点赞有一道 < code > IsLiked< / code > 前置检查,评论没有对应的「这条评论是否已存在」检查——< b > 因为评论本来就可以重复< / b > (同一个人可以对同一个视频发十条内容相同的评论,这在业务上是合法的)。< / p >
< p > < b > 差异三:< code > notifyMentions< / code > 在两条分支里都被调用。< / b > 无论走 MQ 还是降级,「提及通知」都会执行(< code > :62< / code > 与 < code > :89< / code > )。这个函数是本章 11.6 的主题。< / p >
< div class = "box danger" >
< span class = "bt" > 致命的缺失:评论没有任何幂等保护,而它的降级路径会重复写入< / span >
点赞之所以能扛住重复,是因为 < code > likes< / code > 表有联合唯一索引 < code > idx_like_video_account< / code > ——重复插入会被数据库拒绝,代码把它翻译成「已经点过赞了」。< b > 评论表没有任何唯一约束< / b > ( < code > comment_entity.go:5-12< / code > : < code > Username< / code > 、< code > VideoID< / code > 、< code > AuthorID< / code > 都只有普通索引),所以:< br >
• 降级事务里的 < code > tx.Create(comment)< / code > < b > 无条件插入< / b > ,不做任何去重;< br >
• worker 侧的 < code > applyPublish< / code > 同样 < b > 无条件< / b > < code > CreateComment< / code > ( < code > commentworker.go:120-122< / code > ) ; < br >
• 两者都会各自把 < code > popularity< / code > < code > +1< / code > 。< br >
< b > 只要同一条评论事件被处理两次,数据库里就会出现两条一模一样的评论,并且热度多加一次。< / b > 什么情况会处理两次?① MQ 发布成功但客户端超时重发请求(客户端重试 → 两条独立事件);② 发布方认为失败、实际成功(< code > PublishJSON< / code > 没有 publisher confirm, 见第 12 章, broker 已收到但发布方超时),于是 API 走降级直写、worker 后来又消费了那条消息 → < b > 一次用户操作,两条评论< / b > 。< br >
这个组合被项目缺陷报告记为 < b > P0-4< / b > ,是全项目剩余最高等级的问题。修法的方向是幂等表(< code > processed_events(event_id, consumer)< / code > )或给评论加业务唯一键;注意所有事件里其实< b > 都带了 < code > event_id< / code > < / b > ( < code > commentMQ.go< / code > 的 < code > CommentEvent.EventID< / code > ,由 < code > newEventID(16)< / code > 生成),只是< b > 四个 worker 没有一个去读它< / b > 。
< / div >
< p > 评论删除路径短得多,但它的取舍值得单独说:< / p >
< pre data-lang = "go" data-name = "backend/internal/video/comment_service.go:93-110" > func (s *CommentService) Delete(ctx context.Context, commentID uint, accountID uint) error {
comment, err := s.repo.GetByID(ctx, commentID)
if err != nil {
return err
}
if comment == nil {
return errors.New("comment not found")
}
if comment.AuthorID != accountID {
return apierror.ErrUnauthorized
}
if s.commentMQ != nil {
if err := s.commentMQ.Delete(ctx, commentID); err == nil {
return nil
}
}
return s.repo.DeleteComment(ctx, comment)
}< / pre >
< p > < b > ① 权限检查用 < code > apierror.ErrUnauthorized< / code > ,所以能正确映射成 401< / b > (对比 < code > VideoService.Delete< / code > 里同样用 < code > ErrUnauthorized< / code > , 但「video not found」是裸 < code > errors.New< / code > → 500) 。< / p >
< p > < b > ② 删除走 MQ 时不做任何补偿。< / b > < code > commentMQ.Delete< / code > 成功就 < code > return nil< / code > ,剩下的交给 < code > CommentWorker.applyDelete< / code > ——而它< b > 只删评论行< / b > ( < code > commentworker.go:126-138< / code > )。所以删除评论:< b > 不回退 < code > popularity< / code > < / b > ( 10.5 节详述过)、< b > 不删除它产生的 @提及通知< / b > 。< b > 这两件事在点赞的对应路径里都是做了的< / b > ( < code > Unlike< / code > 有完整的 < code > -1< / code > ),评论路径则完全没有。< / p >
< p > < b > ③ 删除的幂等性由 < code > GetByID< / code > 返回 nil 兜住。< / b > 消息重复消费时第二次会拿到 < code > nil< / code > 并返回 < code > "comment not found"< / code > ——虽然名字是「未找到」,但它实际上起到「已删除,忽略」的作用。删除路径因此比发布路径安全。< / p >
2026-10-19 11:16:29 +08:00
< h3 id = "sec-11-3" > 11.3 关注:反过来的 DB-first + MQ 仅通知< / h3 >
2026-10-19 13:08:58 +08:00
< p > 现在到了本章最值得注意的不一致。关注( follow) 的写入顺序与点赞< b > 完全相反< / b > : < / p >
< pre data-lang = "go" data-name = "backend/internal/social/service.go:23-58" > func (s *SocialService) Follow(ctx context.Context, social *Social) error {
_, err := s.accountrepo.FindByID(ctx, social.FollowerID)
if err != nil {
return err
}
_, err = s.accountrepo.FindByID(ctx, social.VloggerID)
if err != nil {
return err
}
if social.FollowerID == social.VloggerID {
return errors.New("can not follow self")
}
isFollowed, err := s.repo.IsFollowed(ctx, social)
if err != nil {
return err
}
if isFollowed {
return errors.New("already followed")
}
// 先写 DB, 确保数据持久化
if err := s.repo.Follow(ctx, social); err != nil {
return err
}
// DB 成功后,失效该用户的关注列表缓存
s.invalidateFollowingFeedCache(context.Background(), social.FollowerID)
// 最后发 MQ( 用于通知) , 失败只记日志不影响业务
if s.socialMQ != nil {
if err := s.socialMQ.Follow(ctx, social.FollowerID, social.VloggerID); err != nil {
log.Printf("social MQ Follow 发布失败: %v", err)
}
}
return nil
}< / pre >
< p > 三行注释把设计意图写得很清楚,而且< b > 三行注释描述的都是反过来的做法< / b > : < / p >
< p > < b > ① < code > // 先写 DB, 确保数据持久化< / code > ——数据库是唯一真相来源,不等 MQ。< / b > 关注关系立即落库,所以< b > 用户马上就能看到自己的操作生效< / b > (关注后立刻刷新页面,粉丝列表里已经有了)。这正是点赞缺少的性质(见 11.7)。< / p >
< p > < b > ② < code > // DB 成功后,失效该用户的关注列表缓存< / code > ——缓存失效在 MQ 之前。< / b > 因为「关注流」缓存(< code > feed:listByFollowing:…< / code > )读的就是数据库里的关注关系,所以必须在数据库已经更新之后立刻失效,否则用户会看到过期的关注流。注意这里用的是 < code > context.Background()< / code > 而不是请求的 < code > ctx< / code > ——< b > 和 10.2 节 < code > UpdatePopularityCache< / code > 里的选择一样< / b > :即使请求已经结束,失效也必须做完。< / p >
< p > < b > ③ < code > // 最后发 MQ( 用于通知) , 失败只记日志不影响业务< / code > ——MQ 在这里不是「写入通道」,只是「通知通道」。< / b > 这是与点赞最本质的区别:点赞的 MQ 消息< b > 承载业务数据本身< / b > (点赞关系要落库),所以它失败必须降级直写;关注的 MQ 消息< b > 只承载一个通知< / b > (「某某关注了你」),所以它失败只记日志——关注关系本身早就写好了,丢掉的只是一条通知。< / p >
< p > 理解了这一点,「为什么关注是 DB-first」就有了答案: < b > 因为关注链路的 MQ 不承担写入职责,所以没有必要把 DB 写入押后到 MQ 成功之后。< / b > 而 < code > socialworker< / code > 里那段「再写一次数据库」的代码就变成了纯粹的冗余。< / p >
< pre data-lang = "go" data-name = "backend/internal/worker/socialworker.go:95-113( 外部依据见 docs/ISSUES-REPORT.md P1-4) " > // worker 侧同样会尝试写入 socials 表;
// 若重复关注, 1062 冲突被 errors.As(...).Number == 1062 吞掉,
// 因此这里既不会报错,也不会产生第二条记录。< / pre >
< div class = "box warn" >
< span class = "bt" > 这条 DB-first 路径上有两处并发缺陷< / span >
< b > ① 重复关注会把数据库错误抛给用户。< / b > < code > repo.Follow< / code > ( < code > social/repo.go:18-20< / code > )直接 < code > Create< / code > ,没有 < code > InsertIgnore< / code > 之类的处理。第 39 行的 < code > IsFollowed< / code > 预检查在并发下形同虚设(和 11.1 的点赞预检查同理),于是两个并发关注请求中,第二个会拿到 MySQL 1062 原始错误——而 handler 会把它变成 < b > 500< / b > ,错误信息里甚至带着数据库原文。对比点赞:点赞把 1062 翻译成了 < code > "user has liked this video"< / code > 。< b > 同一个团队、同一种冲突、两处不同的处理。< / b > < br >
< b > ② 取关是「先查后删」,两步之间没有事务。< / b > < code > Unfollow< / code > ( < code > social/service.go:69-80< / code > )先 < code > IsFollowed< / code > 再 < code > repo.Unfollow< / code > ,后者按条件 < code > DELETE< / code > 。两个并发取关请求里,第二个的 < code > RowsAffected< / code > 是 0——但 < code > repo.Unfollow< / code > 不检查这个返回值,所以它< b > 静默成功< / b > ,返回 200。这与 worker 路径的行为还不一致( worker 靠 1062/0 行判断)。报告记为 < b > P1-4< / b > 。
< / div >
< p > 把三条路径放在一起,就得到本章的核心对照表:< / p >
< div class = "tablewrap" >
< table >
< thead > < tr > < th > 维度< / th > < th > 点赞< / th > < th > 评论< / th > < th > 关注< / th > < / tr > < / thead >
< tbody >
< tr > < td > 写入顺序< / td > < td > < b > MQ-first< / b > :先发 < code > like.events< / code > < / td > < td > < b > MQ-first< / b > :先发 < code > comment.events< / code > < / td > < td > < b > DB-first< / b > :先写 < code > socials< / code > < / td > < / tr >
< tr > < td > MQ 的角色< / td > < td > 业务写入通道< / td > < td > 业务写入通道< / td > < td > < b > 仅通知通道< / b > < / td > < / tr >
< tr > < td > MQ 失败时< / td > < td > 降级直写数据库(事务)< / td > < td > 降级直写数据库(事务)< / td > < td > < b > 只记日志< / b > ,业务已成功< / td > < / tr >
< tr > < td > 幂等保护< / td > < td > 唯一索引 < code > idx_like_video_account< / code > + < code > isDupKey< / code > 翻译< / td > < td > < b > 无< / b > ( P0-4) < / td > < td > 唯一索引 < code > idx_social_follower_vlogger< / code > ,但 < b > 1062 直接抛给用户< / b > < / td > < / tr >
< tr > < td > 缓存失效< / td > < td > 靠 < code > UpdatePopularityCache< / code > 顺带删 detail/entity< / td > < td > 同上< / td > < td > 显式 < code > DelByPattern< / code > 关注流缓存< / td > < / tr >
< tr > < td > 删/取关是否回退热度< / td > < td > < b > 会< / b > ( < code > -1< / code > + < code > GREATEST< / code > ) < / td > < td > < b > 不会< / b > < / td > < td > 不涉及热度< / td > < / tr >
< tr > < td > 用户能否读到自己刚写的< / td > < td > < b > 可能读不到< / b > (异步)< / td > < td > < b > 可能读不到< / b > (异步)< / td > < td > < b > 能< / b > (同步)< / td > < / tr >
< / tbody >
< / table >
< / div >
< p > 这张表回答了本章标题里的「差异」:< b > 三条路径的差异不是随机的, 而是「MQ 承担什么职责」决定的。< / b > MQ 承担业务写入, 就必须有降级直写、必须有幂等、必然带来读写延迟; MQ 只承担通知,就可以先写库、失败只记日志、读写立即可见。项目里两种模式并存,而模式的选择写在注释里、没有写在任何设计文档里——这是最容易被误读的地方。< / p >
2026-10-19 11:16:29 +08:00
< h3 id = "sec-11-4" > 11.4 降级矩阵: MQ 或 Redis 挂掉会发生什么< / h3 >
2026-10-19 13:08:58 +08:00
< p > 现在把所有依赖的开关组合起来,看看系统在不同故障下的行为。这张矩阵是把 11.1– 11.3 的代码分支穷举出来的结果,也是「这个项目为什么能在基础设施不全时半可用」的完整答案。< / p >
< div class = "tablewrap" >
< table >
< thead > < tr > < th > 故障< / th > < th > 点赞 / 评论< / th > < th > 关注< / th > < th > Feed 与热榜< / th > < / tr > < / thead >
< tbody >
< tr >
< td > < b > RabbitMQ 未启用< / b > ( < code > rmq == nil< / code > ,启动时 Dial 失败)< / td >
< td > 5 个 publisher 全为 nil → < code > mysqlEnqueued< / code > 与 < code > redisEnqueued< / code > 都是 false → < b > 两路降级都执行< / b > :事务直写 < code > likes< / code > /< code > comments< / code > + 两列计数,并直写 Redis 热度。< b > 功能完整,只是失去异步解耦< / b > < / td >
< td > < code > socialMQ< / code > 为 nil → 跳过 MQ。< b > 关注照常成功,只是没有通知< / b > < / td >
< td > 时间线 ZSET 不再由 consumer 写入(< code > StartConsumer< / code > 未启动);最新流退化为纯 MySQL 查询< / td >
< / tr >
< tr >
< td > < b > RabbitMQ 连接断开< / b > ( < code > rmq != nil< / code > 但 < code > Healthy() == false< / code > ) < / td >
< td > 发布调用会阻塞在连接管理器的 < code > WaitReady< / code > 里(第 12 章详述),直到< b > 调用方的 ctx 结束< / b > ; handler 传的是 < code > c.Request.Context()< / code > , 所以上限就是客户端连接寿命。ctx 取消后降级分支才开始执行——而那时 < code > ctx< / code > 已废弃,< b > 直写数据库同样失败< / b > < / td >
< td > DB 写入不受影响(不经过 MQ) , < b > 关注依然成功< / b > ; < code > socialMQ.Follow< / code > 返回错误 → 只记一行日志< / td >
< td > 读取路径不依赖 MQ, Feed 正常;热榜读 Redis 快照仍然可用< / td >
< / tr >
< tr >
< td > < b > Redis 不可用< / b > ( < code > cache == nil< / code > ) < / td >
< td > 若 MQ 正常:< code > popularityMQ.Update< / code > 依然成功(它只发消息),但消费端 < code > PopularityWorker< / code > < b > 根本没启动< / b > ( < code > cmd/worker/main.go:171-175< / code > 仅在 < code > cache != nil< / code > 时启动)→ 事件被消费后 < code > UpdatePopularityCache< / code > 直接 return → < b > 热度静默丢失< / b > ; DB 轨不受影响< / td >
< td > 不受影响(关注不写缓存,只是 < code > DelByPattern< / code > 被 < code > cache == nil< / code > 提前 return) < / td >
< td > 三级缓存的 L1/L2 全失效 → 每次请求都落 L3 查 MySQL; < code > listByPopularity< / code > 退回 DB 兜底排序< / td >
< / tr >
< tr >
< td > < b > MQ 与 Redis 同时不可用< / b > < / td >
< td > 两个 publisher 都是 nil( MQ 挂了时构造出的 publisher 为 nil) → 两路降级都走 → 数据库直写成功。< b > 写路径完全可用< / b > < / td >
< td > 同「MQ 未启用」行< / td >
< td > 退回纯 MySQL: 能读最新流与点赞榜, 热榜退化为按 < code > popularity< / code > 列排序< / td >
< / tr >
< tr >
< td > < b > 数据库不可用< / b > < / td >
< td > < b > 全链路失败< / b > 。注意:即使 MQ 正常,< code > Like< / code > 的第 39 行 < code > VideoRepo.IsExist< / code > 也要查库,所以点赞在数据库挂掉时连「发消息」都到不了< / td >
< td > 同样失败(< code > FindByID< / code > × 2 需要数据库)< / td >
< td > Feed 全部失败< / td >
< / tr >
< / tbody >
< / table >
< / div >
< div class = "box note" >
< span class = "bt" > 降级矩阵里最重要的一行是「MQ 连接断开」< / span >
这一行的行为< b > 不是「快速失败 + 降级」,而是「阻塞等待」< / b > 。原因在连接管理器的设计:< code > PublishJSON< / code > → < code > publisherChannel(ctx)< / code > → < code > Session(ctx)< / code > → < code > WaitReady(ctx)< / code > ,而 < code > WaitReady< / code > 会在连接不可用时一直等到 < code > ctx.Done()< / code > 。它的本意是「MQ 短暂抖动时不要立刻失败,等一下就好」——这在与 < code > context.Background()< / code > 搭配时是正确的(比如 Outbox 轮询器就刻意用 < code > context.Background()< / code > + < b > 5 秒超时< / b > ,见第 8 章),但< b > 与请求上下文搭配时,等待上限变成了客户端耐心< / b > 。< br >
后果是: broker 挂掉时,点赞接口不会立刻回退到直写数据库,而是先挂住。等到客户端超时断开、< code > c.Request.Context()< / code > 被取消,降级分支才开始跑——此时 < code > db.WithContext(ctx)< / code > 里的 < code > ctx< / code > 已经取消,< b > 直写也会失败< / b > 。也就是说「降级直写」这个能力在「阻塞等待」的路径上很难真正生效。< br >
这是一个< b > 组合缺陷< / b > :单独看 < code > WaitReady< / code > 与单独看降级分支都没问题,是「阻塞式等待 + 用请求 ctx 做超时 + 降级复用同一个 ctx」三件事叠加出来的。
< / div >
< p > 最后是错误码层面的降级。三个 handler 对服务层错误的映射各不相同,这直接决定了用户看到什么:< / p >
< div class = "tablewrap" >
< table >
< thead > < tr > < th > 错误场景< / th > < th > 服务层返回< / th > < th > 映射结果< / th > < th > 位置< / th > < / tr > < / thead >
< tbody >
< tr > < td > 重复点赞< / td > < td > < code > errors.New("user has liked this video")< / code > < / td > < td > < b > 500< / b > < / td > < td > < code > like_handler.go:39-42< / code > < / td > < / tr >
< tr > < td > 取消未点赞的视频< / td > < td > < code > errors.New("user has not liked this video")< / code > < / td > < td > < b > 500< / b > < / td > < td > < code > like_handler.go:67-70< / code > < / td > < / tr >
< tr > < td > 点赞不存在的视频< / td > < td > < code > errors.New("video not found")< / code > < / td > < td > < b > 500< / b > (应为 404) < / td > < td > < code > like_handler.go:39-42< / code > < / td > < / tr >
< tr > < td > 评论内容为空< / td > < td > < code > errors.New("content is required")< / code > < / td > < td > < code > ClassifyHTTPStatus< / code > → < b > 500< / b > (应为 400) < / td > < td > < code > comment_handler.go< / code > < / td > < / tr >
< tr > < td > 删除他人的评论< / td > < td > < code > apierror.ErrUnauthorized< / code > < / td > < td > < b > 401< / b > ✓< / td > < td > < code > comment_service.go:102< / code > < / td > < / tr >
< tr > < td > 关注自己< / td > < td > < code > errors.New("can not follow self")< / code > < / td > < td > < code > ClassifyHTTPStatus< / code > → < b > 500< / b > (应为 400) < / td > < td > < code > social/handler.go< / code > < / td > < / tr >
< tr > < td > 重复关注< / td > < td > < code > errors.New("already followed")< / code > 或 MySQL < b > 1062 原文< / b > < / td > < td > < b > 500< / b > ,且可能泄露数据库错误文本< / td > < td > < code > social/service.go:40< / code > < / td > < / tr >
< / tbody >
< / table >
< / div >
< p > 这张表说明 < code > apierror.ClassifyHTTPStatus< / code > 这套「按哨兵错误分类」的机制< b > 只在有人记得用哨兵错误时才起作用< / b > : < code > ErrUnauthorized< / code > 被使用了(所以权限错误返回 401 ✓),而 < code > ErrValidation< / code > 在这三个域里< b > 一次都没被使用< / b > ——所有参数/业务校验都用了裸 < code > errors.New< / code > ,于是统统落到 < code > default< / code > 分支,返回 500。用户看到的「参数错误」与「服务器崩了」在状态码上无法区分( 报告记为 < b > P1-5< / b > )。< / p >
2026-10-19 11:16:29 +08:00
< h3 id = "sec-11-5" > 11.5 三个 Worker 的落库逻辑与计数副作用< / h3 >
2026-10-19 13:08:58 +08:00
< p > MQ 成功之后,落库的责任转移到了 worker 进程。三个 worker 的 < code > process< / code > 骨架完全一样:反序列化 → 按 < code > event.Action< / code > 分派 → 调用对应的 apply 函数;反序列化失败统一 < code > return nil< / code > ( < b > 视为成功,直接丢弃< / b > )。< / p >
< pre data-lang = "go" data-name = "backend/internal/worker/likeworker.go:85-103" > func (w *LikeWorker) process(ctx context.Context, body []byte) error {
var evt rabbitmq.LikeEvent
if err := json.Unmarshal(body, & evt); err != nil {
// 解析事件失败,直接丢弃
return nil
}
if evt.UserID == 0 || evt.VideoID == 0 {
return nil
}
switch evt.Action {
case "like":
return w.applyLike(ctx, evt.UserID, evt.VideoID)
case "unlike":
return w.applyUnlike(ctx, evt.UserID, evt.VideoID)
default:
return nil
}
}< / pre >
< p > < b > 注意「解析失败返回 nil」这个选择。< / b > 它把一条无法理解的消息当成了「处理成功」,于是调用方会 < code > Ack< / code > 掉它。这是刻意的(一条格式错误的消息重试一万次也不会变正确),但也意味着< b > 任何一次事件结构变更(改字段名、改类型)都会让旧格式的在途消息被静默丢弃< / b > ,而且不回死信队列。全项目 5 个 worker 都是这么写的。< / p >
< p > 点赞 worker 的落库逻辑是全项目幂等做得最完整的一处:< / p >
< pre data-lang = "go" data-name = "backend/internal/worker/likeworker.go:105-153" > func (w *LikeWorker) applyLike(ctx context.Context, userID, videoID uint) error {
ok, err := w.videos.IsExist(ctx, videoID)
if err != nil {
return err
}
if !ok {
return nil
}
created, err := w.likes.LikeIgnoreDuplicate(ctx, & video.Like{
VideoID: videoID,
AccountID: userID,
CreatedAt: time.Now(),
})
if err != nil {
return err
}
if !created {
return nil
}
if err := w.videos.ChangeLikesCount(ctx, videoID, 1); err != nil {
return err
}
return w.videos.ChangePopularity(ctx, videoID, 1)
}
func (w *LikeWorker) applyUnlike(ctx context.Context, userID, videoID uint) error {
ok, err := w.videos.IsExist(ctx, videoID)
if err != nil {
return err
}
if !ok {
return nil
}
deleted, err := w.likes.DeleteByVideoAndAccount(ctx, videoID, userID)
if err != nil {
return err
}
if !deleted {
return nil
}
if err := w.videos.ChangeLikesCount(ctx, videoID, -1); err != nil {
return err
}
return w.videos.ChangePopularity(ctx, videoID, -1)
}< / pre >
< p > 这段代码的关键在于 < b > < code > created< / code > / < code > deleted< / code > 这两个返回值决定了要不要动计数< / b > : < / p >
< ul >
< li > < code > LikeIgnoreDuplicate< / code > 在遇到 1062 时返回 < code > (false, nil)< / code > ——「已存在,但不是错误」。于是 < code > if !created { return nil }< / code > 让< b > 重复的点赞事件不产生任何计数变化< / b > 。这是正确的幂等:无论同一条 < code > like.like< / code > 消息被消费几次,< code > likes_count< / code > 与 < code > popularity< / code > 都只加一次。< / li >
< li > < code > DeleteByVideoAndAccount< / code > 返回 < code > RowsAffected > 0< / code > , < code > if !deleted { return nil }< / code > 同理——重复的取消点赞事件不会把计数减两次。< / li >
< li > 视频不存在时 < code > return nil< / code > ( < b > 不是错误< / b > ):消息被正常 < code > Ack< / code > 。这是合理的——视频已经被删了,这条点赞事件没有意义。< / li >
< / ul >
< p > 对比评论 worker, 相同的结构却< b > 没有等价的那一道闸门< / b > : < / p >
< pre data-lang = "go" data-name = "backend/internal/worker/commentworker.go:101-138" > func (w *CommentWorker) applyPublish(ctx context.Context, evt *rabbitmq.CommentEvent) error {
if evt == nil || evt.VideoID == 0 || evt.AuthorID == 0 || strings.TrimSpace(evt.Content) == "" {
return nil
}
ok, err := w.videos.IsExist(ctx, evt.VideoID)
if err != nil {
return err
}
if !ok {
return nil
}
c := & video.Comment{
Username: strings.TrimSpace(evt.Username),
VideoID: evt.VideoID,
AuthorID: evt.AuthorID,
Content: strings.TrimSpace(evt.Content),
}
if err := w.comments.CreateComment(ctx, c); err != nil {
return err
}
return w.videos.ChangePopularity(ctx, evt.VideoID, 1)
}
func (w *CommentWorker) applyDelete(ctx context.Context, evt *rabbitmq.CommentEvent) error {
if evt == nil || evt.CommentID == 0 {
return nil
}
c, err := w.comments.GetByID(ctx, evt.CommentID)
if err != nil {
return err
}
if c == nil {
return nil
}
return w.comments.DeleteComment(ctx, c)
}< / pre >
< p > < code > applyPublish< / code > 里< b > 没有 < code > created< / code > 这样的返回值可以依赖< / b > ,因为 < code > CreateComment< / code > 是无条件 < code > INSERT< / code > ,数据库不会告诉它「这条已经存在了」——< code > comments< / code > 表根本没有能表达「这条评论已经存在」的约束。所以重复消费 = 重复评论 + 重复加热度。这是 11.2 节那个缺陷在 worker 侧的同一张脸。< / p >
< p > < code > applyDelete< / code > 则安全得多:< code > GetByID< / code > 返回 < code > nil< / code > 时直接 < code > return nil< / code > ,重复消费第二次就什么都不做。注意它< b > 连视频存在性检查都不做< / b > ——删除一条挂在已删视频下的评论,业务上是无害的。< / p >
< div class = "box danger" >
< span class = "bt" > 计数的副作用:两个计数列,两次独立 UPDATE, 没有事务< / span >
三个 worker 里凡是动计数的地方,都是< b > 连续两次独立的 UPDATE< / b > : < br >
< pre data-lang = "go" data-name = "backend/internal/worker/likeworker.go:126-129" > if err := w.videos.ChangeLikesCount(ctx, videoID, 1); err != nil {
return err
}
return w.videos.ChangePopularity(ctx, videoID, 1)< / pre >
如果第一条成功、第二条失败(例如数据库瞬时抖动),那么这个视频的 < code > likes_count< / code > 已经 < code > +1< / code > ,而 < code > popularity< / code > 没变。函数返回错误 → < code > handleDelivery< / code > 会重试(最多 3 次)→ 重试时 < code > LikeIgnoreDuplicate< / code > 返回 < code > created = false< / code > → < code > return nil< / code > , < b > 于是那次缺失的 < code > popularity +1< / code > 永远不会被补上< / b > 。< br >
这是一个精确的「重试不收敛」缺陷:幂等闸门(< code > !created → return nil< / code > )挡住了重复计数,但也同时挡住了「补做未完成的那一半」。要修它,两次 UPDATE 必须放在< b > 同一个事务< / b > 里(< code > ChangeLikesCount< / code > 与 < code > ChangePopularity< / code > 共用一个 < code > tx< / code > )。项目缺陷报告把这类问题归为 < b > A-2「事务边界不足」< / b > 。< br >
还要注意 < code > ChangeLikesCount< / code > 与 < code > ChangePopularity< / code > 内部用的是 < code > GREATEST(col + ?, 0)< / code > ( < code > video_repo.go:88-95< / code > ),所以计数不会被减成负数——这个保护是有的,但< b > 它在 worker 路径与降级直写路径上各写了一遍< / b > ,两处都不能忘。
< / div >
< p > 三个 worker 的对照:< / p >
< div class = "tablewrap" >
< table >
< thead > < tr > < th > Worker< / th > < th > 消费队列 / 路由键< / th > < th > 幂等机制< / th > < th > 改动的计数< / th > < th > 事务< / th > < / tr > < / thead >
< tbody >
< tr > < td > < code > LikeWorker< / code > < / td > < td > < code > like.events< / code > / < code > like.like< / code > 、< code > like.unlike< / code > < / td > < td > < b > 唯一索引< / b > + < code > LikeIgnoreDuplicate< / code > 的 < code > created< / code > / < code > DeleteByVideoAndAccount< / code > 的 < code > deleted< / code > < / td > < td > < code > likes_count< / code > 与 < code > popularity< / code > 各 ±1< / td > < td > < b > 无< / b > (两条独立 UPDATE) < / td > < / tr >
< tr > < td > < code > CommentWorker< / code > < / td > < td > < code > comment.events< / code > / < code > comment.publish< / code > 、< code > comment.delete< / code > < / td > < td > 发布< b > 无< / b > ;删除靠 < code > GetByID == nil< / code > < / td > < td > 发布 < code > popularity< / code > +1; 删除< b > 什么都不改< / b > < / td > < td > < b > 无< / b > < / td > < / tr >
< tr > < td > < code > SocialWorker< / code > < / td > < td > < code > social.events< / code > / < code > social.follow< / code > 、< code > social.unfollow< / code > < / td > < td > 1062 被吞掉(< code > errors.As< / code > + < code > Number == 1062< / code > ) < / td > < td > < b > 不改计数< / b > (粉丝数靠 < code > COUNT(*)< / code > 实时算)< / td > < td > < b > 无< / b > (单条写入)< / td > < / tr >
< / tbody >
< / table >
< / div >
< p > 最后一行值得单独注意:< b > 关注关系没有冗余计数列< / b > 。< code > follower_count< / code > / < code > vlogger_count< / code > 是通过 < code > social/repo.go< / code > 的 < code > CountFollowers< / code > / < code > CountVloggers< / code > 每次 < code > SELECT COUNT(*)< / code > 得到的,而不是维护在 < code > accounts< / code > 表上。< b > 这让关注域天生不会出现「计数漂移」< / b > ——它没有计数可以漂移。代价是每次查粉丝数都要一次聚合查询(有 < code > idx_social_vlogger< / code > 索引可用,成本可接受)。这是一个很好的反例:< b > 「不引入派生数据」是消除一致性问题的终极手段< / b > ,而点赞与评论选择了引入派生列(< code > likes_count< / code > / < code > popularity< / code > ),于是就必须承担漂移与对账问题。< / p >
2026-10-19 11:16:29 +08:00
< h3 id = "sec-11-6" > 11.6 提及通知:唯一绕过 MQ 的写入路径< / h3 >
2026-10-19 13:08:58 +08:00
< p > 评论里可以写 < code > @某人< / code > 。这个功能的实现方式在整个项目里是< b > 独一无二的< / b > :它不经过 MQ, 直接向 < code > notifications< / code > 表写数据。先看正则:< / p >
< pre data-lang = "go" data-name = "backend/internal/video/comment_service.go:123-158" > var mentionRegex = regexp.MustCompile(`@(\w+)`)
func (s *CommentService) notifyMentions(ctx context.Context, comment *Comment) {
matches := mentionRegex.FindAllStringSubmatch(comment.Content, -1)
if len(matches) == 0 {
return
}
seen := make(map[string]bool)
for _, m := range matches {
username := m[1]
if seen[username] || username == comment.Username {
continue
}
seen[username] = true
var accID uint
if err := s.repo.db.WithContext(ctx).Table("accounts").Where("username = ?", username).Select("id").Scan(& accID).Error; err != nil || accID == 0 {
continue
}
notif := struct {
RecipientID uint
SenderID uint
Type string
TargetID uint
Content string
}{
RecipientID: accID,
SenderID: comment.AuthorID,
Type: "mention",
TargetID: comment.VideoID,
Content: comment.Username + " 在评论中提到了你",
}
if err := s.repo.db.WithContext(ctx).Table("notifications").Create(& notif).Error; err != nil {
log.Printf("create mention notification failed: %v", err)
}
}
}< / pre >
< p > 这个函数有< b > 四个设计问题< / b > ,每一个都能独立作为「为什么规则写进 MQ 更好」的论据。< / p >
< p > < b > ① 正则只支持 ASCII 用户名。< / b > < code > @(\w+)< / code > 里的 < code > \w< / code > 在 Go 正则中等价于 < code > [0-9A-Za-z_]< / code > ——< b > 只认英文、数字、下划线< / b > 。所以 < code > @张三< / code > 完全匹配不到,中文用户永远收不到提及通知。对比一下标签抽取用的 < code > #([\p{L}\p{N}_]+)< / code > ( < code > tag_entity.go< / code > ),那个用了 Unicode 字符类、支持中文。< b > 同一个项目里两处相似的文本抽取,一处国际化、一处没有< / b > ,说明这是遗漏而不是取舍。< / p >
< p > < b > ② 它绕过了 MQ, 因此在 API 进程里同步执行。< / b > 评论发布接口在返回前会:(a) 用正则扫一遍内容;(b) 对每个不同的被提及用户查一次 < code > accounts< / code > 表;(c) 对每个用户插一行通知。这些都在< b > 请求线程内、事务之外< / b > 。一条带了 10 个 < code > @< / code > 的评论会产生 10 次 < code > SELECT< / code > + 10 次 < code > INSERT< / code > ,全部计入接口响应时间。而且 < code > Create< / code > 失败< b > 只记日志不返回错误< / b > ——所以通知可能丢,而调用方不知道。< / p >
< p > < b > ③ 幂等性靠进程内的 < code > seen< / code > map, 只覆盖「同一条评论里的重复提及」。< / b > < code > seen[username]< / code > 保证一条评论里同一个用户名只通知一次(< code > @a< / code > 写两遍只发一条);< code > username == comment.Username< / code > 保证不通知自己。但< b > 如果同一条评论被处理两次< / b > (正是 11.2 的那个 P0-4 场景),< code > seen< / code > 是新的一份 map, < b > 会再发一遍通知< / b > 。评论重复 → 评论行两条 + 通知两份。< / p >
< div class = "box danger" >
< span class = "bt" > ④ 匿名结构体里没有 < code > CreatedAt< / code > ,所以提及通知的时间是 NULL< / span >
这段代码用来插入的< b > 不是 < code > worker.Notification< / code > 结构体< / b > ,而是一个在函数内部现定义的匿名结构体(< code > :141-153< / code > )。把它和真正的模型对比一下:< br >
< pre data-lang = "go" data-name = "backend/internal/worker/notificationworker.go:15-24" > type Notification struct {
ID uint `gorm:"primaryKey" json:"id"`
RecipientID uint `gorm:"index;not null" json:"recipient_id"`
SenderID uint `gorm:"not null" json:"sender_id"`
Type string `gorm:"type:varchar(50);not null" json:"type"`
TargetID uint `json:"target_id"`
Content string `gorm:"type:varchar(255)" json:"content"`
IsRead bool `gorm:"default:false" json:"is_read"`
CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"`
}< / pre >
模型有 < code > CreatedAt time.Time \`gorm:"autoCreateTime"\`< / code > ,而匿名结构体< b > 根本没有这个字段< / b > 。GORM 的 < code > autoCreateTime< / code > 是通过识别 < code > CreatedAt< / code > 字段来生效的,字段不存在自然就不会被填充——< b > 生成的 INSERT 语句里不包含 < code > created_at< / code > < / b > 。< br >
而 < code > notifications.created_at< / code > 在模型里< b > 没有 < code > not null< / code > 标签< / b > (对比 < code > recipient_id< / code > 、< code > sender_id< / code > 、< code > type< / code > 都显式标了 < code > not null< / code > ),所以它是可空列,未提供值时落到 < code > NULL< / code > 。< br >
后果在读取端:通知列表接口是 < code > ORDER BY created_at DESC LIMIT 50< / code > ( < code > ssehub.go< / code > 的 < code > ListHandler< / code > ) 。MySQL 在 < code > DESC< / code > 排序时把 < code > NULL< / code > 排在< b > 最后< / b > ,所以< b > 所有提及类通知都会沉到列表末尾< / b > ,用户几乎看不到。同时 < code > json< / code > 序列化后 < code > created_at< / code > 是零值时间,前端渲染会显示 < code > 0001-01-01< / code > 一类的结果。< br >
这个缺陷在项目缺陷报告里没有单独列出,因为它藏在「匿名结构体」这个实现细节里——但它说明了一个通用教训:< b > 用 < code > Table(…).Create(& 匿名结构体)< / code > 绕过模型时,模型上所有由 GORM 自动维护的字段(创建时间、更新时间、软删标记)都会静默失效。< / b >
< / div >
< p > 对比一下「正统」的通知路径——< code > NotificationWorker< / code > 的处理逻辑,就能看出差距:< / p >
< div class = "tablewrap" >
< table >
< thead > < tr > < th > 对比项< / th > < th > < code > notifyMentions< / code > (提及)< / th > < th > < code > NotificationWorker< / code > (点赞/评论/关注)< / th > < / tr > < / thead >
< tbody >
< tr > < td > 触发位置< / td > < td > API 进程,< b > 请求线程内< / b > < / td > < td > worker 进程,< b > 消费线程内< / b > < / td > < / tr >
< tr > < td > 是否经过 MQ< / td > < td > < b > 否< / b > < / td > < td > 是(消费 < code > notification.like< / code > / < code > notification.comment< / code > / < code > notification.social< / code > ) < / td > < / tr >
< tr > < td > 用的模型< / td > < td > < b > 匿名结构体< / b > (缺 < code > CreatedAt< / code > ) < / td > < td > 真正的 < code > Notification< / code > 模型(< code > autoCreateTime< / code > 生效)< / td > < / tr >
< tr > < td > 推送 SSE< / td > < td > < b > 不推< / b > ——只写库< / td > < td > 写库后调 < code > hub.Push(recipientID, notif)< / code > 实时推送< / td > < / tr >
< tr > < td > 接收方判断< / td > < td > 靠正则 + 查 < code > accounts< / code > < / td > < td > 查 < code > videos.author_id< / code > ,跳过「自己操作自己」< / td > < / tr >
< tr > < td > 失败处理< / td > < td > 只记日志< / td > < td > 返回错误,走 worker 的重试骨架< / td > < / tr >
< / tbody >
< / table >
< / div >
< p > 最后一行差别最大:< b > 提及通知不会实时推送到前端< / b > 。因为 SSE 推送发生在 < code > NotificationWorker.process< / code > 里(写库之后调 < code > hub.Push< / code > ),而提及通知压根没走 worker。所以被 < code > @< / code > 的用户必须< b > 主动刷新通知列表< / b > 才能看到——在一个已经实现了 SSE 实时推送的系统里,这是一个明显的能力缺口。报告把「提及通知改走 MQ → NotificationWorker」列入了修复路线的第二阶段( 第 11 条)。< / p >
< p > 还有一处小的一致性缺失:< code > notifyMentions< / code > 用 < code > Username< / code > 反查 < code > accounts.id< / code > 时,命名与其他通知的 < code > TargetID< / code > 语义不完全对齐。看 < code > NotificationWorker< / code > 的三条分支:< code > like< / code > 与 < code > comment< / code > 的 < code > TargetID< / code > 是< b > 视频 ID< / b > , < code > follow< / code > 的 < code > TargetID< / code > 是< b > 关注者的账号 ID< / b > 。而提及通知的 < code > TargetID< / code > 是< b > 视频 ID< / b > 。< b > 同一个 < code > target_id< / code > 列在不同 < code > type< / code > 下指向不同的表< / b > ——这是一个多态外键(第 6 章讲过),前端点通知跳转时必须先看 < code > type< / code > 才能决定怎么用这个 ID。< / p >
2026-10-19 11:16:29 +08:00
< h3 id = "sec-11-7" > 11.7 读不到自己的写:异步一致性的用户体验< / h3 >
2026-10-19 13:08:58 +08:00
< p > 本章最后一个问题,也是最容易在面试里被追问的一个:< b > MQ-first 的写路径,用户能不能立刻看到自己的操作?< / b > 答案是不能,而且失败的方式有两种。< / p >
< p > < b > 失败方式一:读接口查不到刚写的记录。< / b > 点赞的读接口直接查数据库:< / p >
< pre data-lang = "go" data-name = "backend/internal/video/like_repo.go:44-52、video/like_service.go:180-186" > // IsLiked 判断某个用户是否已经点赞
func (r *LikeRepository) IsLiked(ctx context.Context, videoID, accountID uint) (bool, error) {
var count int64
if err := r.db.WithContext(ctx).Model(& Like{}).
Where("video_id = ? AND account_id = ?", videoID, accountID).
Count(& count).Error; err != nil {
return false, err
}
return count > 0, nil
}< / pre >
< p > 点赞请求返回 200 时,< code > likes< / code > 表里< b > 很可能还没有这一行< / b > ——它还在队列里等着 < code > LikeWorker< / code > 消费。此时如果客户端立刻调 < code > /like/isLiked< / code > ,会得到 < code > false< / code > ;如果 Feed 接口用 < code > BatchGetLiked< / code > 批量填充 < code > is_liked< / code > ,那个视频显示的也是「未点赞」。< / p >
< p > < b > 失败方式二(更严重):状态检查会拒绝一个合法操作。< / b > < code > Unlike< / code > 的第一道校验是 < code > if !isLiked { return errors.New("user has not liked this video") }< / code > ( < code > like_service.go:130-132< / code > )。用户「点赞 → 立刻取消点赞」时:< / p >
< div class = "cards" >
< div class = "card" >
< h4 > t=0ms: 点赞请求< / h4 >
< p > API 校验通过(数据库里确实没有点赞记录),向 < code > like.events< / code > 发布消息,< b > 返回 200< / b > 。此时 < code > likes< / code > 表仍为空。< / p >
< / div >
< div class = "card" >
< h4 > t=50ms: 取消点赞请求< / h4 >
< p > < code > IsLiked< / code > 查到 < code > count = 0< / code > → < code > !isLiked< / code > 成立 → 返回 < code > "user has not liked this video"< / code > → handler 映射成 < b > 500< / b > 。< / p >
< p > 而 < code > LikeWorker< / code > 此时可能刚好把点赞写进库了——取决于两个进程的调度顺序。< / p >
< / div >
< / div >
< p > 这个竞态的窗口等于「从 API 发布消息到 worker 落库」的延迟,通常是< b > 几十毫秒到几秒< / b > (取决于队列积压与 prefetch) 。在移动端网络下, 用户连点两次同一个心形按钮完全落在这个窗口里。报告把它记为 < b > P2-5「点赞异步落库导致读不到自己的写」< / b > 。< / p >
< div class = "box warn" >
< span class = "bt" > 前端的「乐观更新」正好绕开了这个问题,但方式是被动的< / span >
看前端的点赞实现:< br >
< pre data-lang = "ts" data-name = "frontend/src/composables/useLikeFollow.ts:17-33" > async function toggleLike(item: FeedVideoItem) {
if (!auth.isLoggedIn) return needLogin()
const key = String(item.id)
if (likeBusy[key]) return
likeBusy[key] = true
try {
if (item.is_liked) await likeApi.unlike(item.id)
else await likeApi.like(item.id)
item.is_liked = !item.is_liked
item.likes_count = Math.max(0, item.likes_count + (item.is_liked ? 1 : -1))
} catch (e) {
const msg = e instanceof ApiError ? e.message : String(e)
toast.error(msg)
} finally {
likeBusy[key] = false
}
}< / pre >
注意本地状态是在 < code > await< / code > < b > 返回之后< / b > 才翻转的(< code > :25-26< / code > ),所以它其实是「< b > 服务端确认后更新< / b > 」而不是真正的乐观更新。命名与行为不符(报告记为 < b > F-15< / b > )。< br >
但这恰好也解释了一个现象:< b > 页面上的心形状态与数据库状态可能长期不一致< / b > 。本地翻转了状态,服务端却要等 worker 落库; 如果此时用户刷新页面, Feed 会重新从数据库读 < code > is_liked< / code > ,界面可能「弹回去」。而 < code > likeBusy[key]< / code > 这道按视频 ID 的防重(< code > :20-21< / code > )只防住了< b > 同一个浏览器里< / b > 的连点,防不住「点完立刻刷新」。< br >
真正的乐观更新应该是「立即翻转 + 失败时回滚」,那样连点体验更顺滑但对这个后端更危险(第二次点会打到状态未提交的服务端,直接拿到 500) 。当前的写法在「响应速度」与「错误率」之间选了稳一点的那边。
< / div >
< p > 对比评论:< code > /comment/listAll< / code > 是直接查 < code > comments< / code > 表(< code > GetAllComments< / code > , < code > created_at ASC< / code > , < code > Limit 200< / code > )。发布评论后立刻拉列表,< b > 新评论可能不在里面< / b > ——同样是那个延迟窗口。而评论的前端实现更直接:< / p >
< div class = "tablewrap" >
< table >
< thead > < tr > < th > 操作< / th > < th > 服务端写入< / th > < th > 读接口数据源< / th > < th > 用户能否立刻看到< / th > < / tr > < / thead >
< tbody >
< tr > < td > 点赞< / td > < td > 异步( worker 写 < code > likes< / code > ) < / td > < td > < code > likes< / code > 表 / < code > BatchGetLiked< / code > < / td > < td > < b > 不能< / b > ,本地状态是前端自己翻的< / td > < / tr >
< tr > < td > 取消点赞< / td > < td > 异步< / td > < td > 同上< / td > < td > < b > 不能< / b > ;且紧接着再点赞会撞上 < code > IsLiked< / code > 的预检查 → 500< / td > < / tr >
< tr > < td > 评论< / td > < td > 异步< / td > < td > < code > comments< / code > 表< / td > < td > < b > 不能< / b > ,需要等 worker 落库后重新拉列表< / td > < / tr >
< tr > < td > 删除评论< / td > < td > 异步< / td > < td > 同上< / td > < td > < b > 不能< / b > (列表里可能还留着刚删的那条)< / td > < / tr >
< tr > < td > 关注< / td > < td > < b > 同步< / b > (直接写 < code > socials< / code > ) < / td > < td > < code > socials< / code > 表< / td > < td > < b > 能< / b > ,刷新后立刻可见< / td > < / tr >
< tr > < td > 取消关注< / td > < td > < b > 同步< / b > < / td > < td > 同上< / td > < td > < b > 能< / b > < / td > < / tr >
< / tbody >
< / table >
< / div >
< p > 这张表的最后两行解释了 11.3 节那个「不一致」在< b > 用户体验层面< / b > 的收益:< b > 关注之所以选择 DB-first, 很可能就是因为它处在「用户会立刻看到结果」的界面上< / b > ——关注按钮点完,主页的粉丝/关注数会立刻重算(< code > social< / code > store 的 < code > refreshVloggers()< / code > 会重新拉一次列表),如果这里也是异步的,界面会明显「不跟手」。而点赞与评论共处一个沉浸式播放页,心形与评论数的即时反馈由前端本地状态负责,所以后端可以异步。< / p >
< div class = "box case" >
< span class = "bt" > 从「读不到自己的写」能学到什么< / span >
「用户写的操作自己立刻读不到」在分布式系统里叫 < b > read-your-own-writes 一致性< / b > 缺失,它是异步写入最典型的用户可见代价。三种常见解法:< br >
< b > ① 读时回源到发起方< / b > ——客户端把自己的操作记在本地,展示时优先用本地状态(这个项目的点赞就是这么做的,只不过状态存在内存里,刷新即失效);< br >
< b > ② 写后同步读< / b > ——写接口返回时附带最新状态,客户端用它更新界面(本项目没做);< br >
< b > ③ 关键操作走同步路径< / b > ——像关注那样直接写库(本项目对关注就是这么选的)。< br >
这个项目的现状是「点赞/评论用 ①③ 的混合,关注用 ③」,而< b > 没有一处把这个选择写进文档< / b > 。真正危险的不是「异步写入」,而是< b > 把异步写入与同步读取拼在一起,却假设它们是同步的< / b > ——11.1 里那道 < code > IsLiked< / code > 预检查就是这种假设的产物:它假定「上一次点赞已经落库」,而在这个架构里这个假设并不成立。
< / div >
< div class = "box ok" >
< span class = "bt" > 本章结论速记< / span >
① < b > 点赞< / b > : MQ-first( < code > like.events< / code > + < code > video.popularity.events< / code > 双发),两个独立布尔开关决定两路降级;降级事务用 < code > tx.Select("id").First< / code > 确认视频、< code > isDupKey< / code > 把 1062 翻译成业务错误;< code > Unlike< / code > 用 < code > RowsAffected< / code > 代替预查并靠 < code > GREATEST(…, 0)< / code > 防下溢。< br >
② < b > 评论< / b > :与点赞同构,但< b > 没有任何幂等约束< / b > ——降级事务与 worker 都是无条件 < code > INSERT< / code > ,重复即双写双加热度(< b > P0-4< / b > );删除路径不回退热度、不清理提及通知。< br >
③ < b > 关注< / b > : DB-first, MQ 只负责通知(失败仅日志);缓存失效用 < code > context.Background()< / code > ;并发重复关注会把 1062 抛给用户( 500 + 数据库原文),取关「先查后删」无事务。< br >
④ < b > 降级矩阵< / b > : MQ 未启用 → 两路降级全走, 功能完整; MQ 断连 → 发布调用< b > 阻塞在 < code > WaitReady< / code > < / b > 直到请求 ctx 取消,降级随后因 ctx 已废弃而失败( 组合缺陷) ; Redis 不可用 → < code > PopularityWorker< / code > 根本不启动,热度静默丢失。< br >
⑤ < b > Worker 侧< / b > :点赞靠 < code > created< / code > /< code > deleted< / code > 返回值实现真幂等;评论发布无闸门;两个计数列是< b > 两条独立 UPDATE、无事务< / b > ,重试时会因幂等闸门而无法补做另一半;关注域< b > 不维护计数列< / b > ( < code > COUNT(*)< / code > 实时算),天生无漂移。< br >
⑥ < b > 提及通知< / b > :唯一绕过 MQ 的写入路径(请求线程内同步查库+插库),正则 < code > @(\w+)< / code > < b > 只支持 ASCII< / b > ;用< b > 匿名结构体< / b > 插入导致 < code > created_at< / code > 落 NULL( 列表排序沉底) ; 不推 SSE, 需手动刷新。< br >
⑦ < b > 读不到自己的写< / b > :点赞/评论异步落库,读接口可能查不到;更严重的是「点赞后立刻取消」会撞上 < code > IsLiked< / code > 预检查返回 500; 前端 < code > toggleLike< / code > 在 < code > await< / code > 之后才翻转本地状态(不是真正的乐观更新),刷新即失效。关注走同步路径,因此没有这个问题。
< / div >
2026-10-19 11:16:29 +08:00
< nav class = "pager" >
< a class = "prev" href = "10-popularity.html" > < span class = "k" > ← 上一章< / span > < span class = "v" > 第 10 章 · 热榜与热度:分钟窗口、快照合并与稳定分页< / span > < / a >
< a class = "next" href = "12-mq.html" > < span class = "k" > 下一章 →< / span > < span class = "v" > 第 12 章 · 消息队列与可靠性:连接管理器、拓扑重放与消费循环< / span > < / a >
< / nav >
< p class = "foot" >
VLoop 项目学习 · 第 11 章 点赞 / 评论 / 关注:三条写路径的差异与降级< br >
< a href = "index.html" > 学习地图< / a > · < a href = "part-2.html" > 篇 2 项目拆解< / a > · < a href = "22-cheatsheet.html" > 速查与自测< / a >
< / p >
< / article >
< / main >
< / div >
< button id = "toTop" title = "回到顶部" > ↑< / button >
< script src = "assets/doc.js" > < / script >
< script src = "../../assets/back.js" data-portal-back = "project/VLoop" data-portal-label = "工程项目 › VLoop 项目学习( Go 短视频 Feed 系统)" > < / script >
< / body >
< / html >