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 >
2026-11-02 22:38:31 +08:00
< meta name = "description" content = "把三个互动模块并排比较:点赞的 MQ-first 与唯一索引幂等、评论的幂等键与 request_id、关注反过来的 DB-first, 以及各自的降级分支与计数副作用。" >
2026-10-19 11:16:29 +08:00
< 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 >
2026-11-12 14:15:24 +08:00
< 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 >
2026-10-19 11:16:29 +08:00
< 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-11-12 14:15:24 +08:00
< b > 这一章解决什么:< / b > 点赞、评论、关注都是「用户点一下」,写路径却长成三种形态。< strong > 点赞< / strong > 是 MQ-first: 一条 < code > like.events< / code > 同时驱动点赞行、两个计数列和热度窗口, API 侧只有一个 < code > enqueued< / code > 布尔。< strong > 评论< / strong > 也是 MQ-first, 但多一个由客户端 < code > request_id< / code > 决定的幂等键,重试同一请求不会写出第二条评论。< strong > 关注< / strong > 反过来是 DB-first: < code > SocialService< / code > 里一条 < code > INSERT … ON CONFLICT DO NOTHING< / code > 先落库、< code > RowsAffected< / code > 判出这次是不是真新增,只有真新增才失效关注流缓存、才发 MQ; 那条消息只剩一个消费者, 负责写通知。把三条路径并排放, 才能看清「谁保证幂等、谁只是发消息、MQ 挂了哪条还能走」。
2026-10-19 11:16:29 +08:00
< / div >
2026-11-02 22:38:31 +08:00
< div class = "tablewrap" >
< table >
< thead >
< tr > < th > 动作< / th > < th > 先落库还是先入队< / th > < th > 幂等靠什么< / th > < th > MQ 的角色< / th > < / tr >
< / thead >
< tbody >
< tr > < td > 点赞< / td > < td > 先入队(失败才直写)< / td > < td > 唯一索引 < code > idx_like_video_account< / code > < / td > < td > 唯一的写路径:行、计数、热度都由它带< / td > < / tr >
< tr > < td > 评论< / td > < td > 先入队(失败才直写)< / td > < td > 唯一索引 < code > uk_comments_author_key< / code > + < code > request_id< / code > < / td > < td > 写评论行;热度由消费者补< / td > < / tr >
2026-11-12 14:15:24 +08:00
< tr > < td > 关注< / td > < td > 先落库,再发消息< / td > < td > 唯一索引 < code > idx_social_follower_vlogger< / code > < / td > < td > 驱动通知;消息可丢,失败不影响关注成立< / td > < / tr >
2026-11-02 22:38:31 +08:00
< / tbody >
< / table >
< / div >
2026-10-19 13:08:58 +08:00
2026-11-02 22:38:31 +08:00
< h3 id = "sec-11-1" > < span class = "n" > 11.1< / span > 点赞: MQ-first 与唯一索引幂等< / h3 >
2026-10-19 13:08:58 +08:00
2026-11-02 22:38:31 +08:00
< p > 点赞接口在 API 进程里只做三件事:校验参数、预检是否已点赞、把意图投进 < code > like.events< / code > 。真正改变状态的是 < code > LikeWorker< / code > :它插入点赞行、给 < code > likes_count< / code > 与 < code > popularity< / code > 各加一、再给分钟窗口加一分。因此 API 侧不需要维护第二个布尔量,< code > enqueued< / code > 一个就够——不存在「数据库写成功但热度没写」这种需要单独记账的子支路。< / p >
2026-10-19 13:08:58 +08:00
2026-11-02 22:38:31 +08:00
< pre data-lang = "go" > // backend/internal/video/like_service.go —— Like 的同步段
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")
}
2026-10-19 13:08:58 +08:00
2026-11-02 22:38:31 +08:00
like.CreatedAt = time.Now()
2026-10-19 13:08:58 +08:00
2026-11-02 22:38:31 +08:00
// 意图键只用于日志关联,不参与去重:判重由唯一索引在事务里做。
intentKey, err := NewIntentKey()
if err != nil {
return err
}
2026-10-19 13:08:58 +08:00
2026-11-02 22:38:31 +08:00
enqueued := false
if s.likeMQ != nil {
if err := s.likeMQ.Like(ctx, like.AccountID, like.VideoID, intentKey); err != nil {
log.Printf("like: enqueue like failed, fallback to direct write: %v", err)
} else {
enqueued = true
}
}
if enqueued {
// 入队成功即返回:落库与热榜都由 worker 在同一条事务路径上完成。
return nil
}
2026-10-19 13:08:58 +08:00
2026-11-02 22:38:31 +08:00
created, err := s.repo.ApplyLike(ctx, like)
if err != nil {
return err
}
if !created {
return errors.New("user has liked this video")
}
if err := ApplyHotDelta(ctx, s.cache, like.VideoID, 1, like.CreatedAt); err != nil {
log.Printf("like: 热榜更新失败( 已降级) video=%d: %v", like.VideoID, err)
}
return nil< / pre >
2026-10-19 13:08:58 +08:00
2026-11-02 22:38:31 +08:00
< p > 这段代码有四个容易看漏的点。第一,< code > IsLiked< / code > 预检只负责给出友好错误,并发下两个请求都能通过预检,真正把第二个挡掉的是唯一索引。第二,< code > intent_key< / code > 会写进 < code > LikeEvent.EventID< / code > ,但在点赞里它只用于把 API 日志和 Worker 日志串起来,< em > 不参与判重< / em > ——评论才用它做幂等键。第三,投递成功就 < code > return< / code > , 不直写、不等确认, 这是「MQ-first」的定义: 消息发出即认为动作已被接收。第四, 降级分支里 < code > created< / code > 是权威信号,只有它返回 < code > true< / code > 才允许 < code > ApplyHotDelta< / code > ,否则重复点赞会把热度加两次。< / p >
2026-10-19 13:08:58 +08:00
2026-11-02 22:38:31 +08:00
< p > 幂等落在事务里,形如:< / p >
2026-10-19 13:08:58 +08:00
2026-11-02 22:38:31 +08:00
< pre data-lang = "go" > // backend/internal/video/like_repo.go —— ApplyLike 的事务体
res := tx.Clauses(clause.OnConflict{DoNothing: true}).Create(like)
if res.Error != nil {
return res.Error
}
if res.RowsAffected == 0 {
return nil // 行已存在:两个计数一个都不能动
}
created = true
2026-10-19 13:08:58 +08:00
2026-11-02 22:38:31 +08:00
tx.Model(& Video{}).Where("id = ?", like.VideoID).
UpdateColumn("likes_count", gorm.Expr("GREATEST(likes_count + 1, 0)"))
tx.Model(& Video{}).Where("id = ?", like.VideoID).
UpdateColumn("popularity", gorm.Expr("GREATEST(popularity + 1, 0)"))< / pre >
2026-10-19 13:08:58 +08:00
2026-11-02 22:38:31 +08:00
< p > < code > GREATEST(..., 0)< / code > 不是装饰:取消点赞与重复投递交错时,计数可能被减到负数,这个夹取让「计数为负」这种不可能状态永远不会出现在库里。取消点赞调用 < code > ApplyUnlike< / code > ,它返回被删的那一行,热度按 < code > row.CreatedAt< / code > 减回< b > 点赞发生的那一分钟< / b > ,而不是按此刻的钟——窗口是滚动的,减错桶会留下一个永远偏高的旧桶。< / p >
2026-10-19 13:08:58 +08:00
< div class = "box danger" >
2026-11-02 22:38:31 +08:00
< div class = "box-t" > 「已点过赞」返回 500, 不是 409< / div >
2026-11-03 13:07:55 +08:00
< p > < code > like_handler.go< / code > 只对参数绑定与鉴权失败调用 < code > apierror.ClassifyHTTPStatus< / code > ; < code > lh.service.Like< / code > 与 < code > lh.service.Unlike< / code > 返回错误时它直接写 < code > c.JSON(500, ...)< / code > ,不再分类。而 < code > "user has liked this video"< / code > 、< code > "user has not liked this video"< / code > 、< code > "video not found"< / code > 都是普通 < code > errors.New< / code > ,即使交给分类器也只会得到 500。前端不能靠状态码判断「重复点赞」, 只能把 500 当作可重试或直接以本地状态为准。这是当前实现的真实行为,不是设计意图。< / p >
2026-10-19 13:08:58 +08:00
< / div >
2026-11-02 22:38:31 +08:00
< h3 id = "sec-11-2" > < span class = "n" > 11.2< / span > 评论:同构写路径与幂等键< / h3 >
2026-10-19 13:08:58 +08:00
2026-11-02 22:38:31 +08:00
< p > 评论与点赞同构:先校验、再投 < code > comment.events< / code > 、失败才直写。区别在幂等键的来源——评论的键来自客户端。HTTP 层把请求体里的 < code > request_id< / code > 直接当作 < code > IdempotencyKey< / code > ;如果客户端没传,服务端生成一个,于是「重试」就变成了一条新评论。< / p >
< pre data-lang = "go" > // backend/internal/video/comment_service.go —— Publish 的同步段
key, err := ResolveIntentKey(comment.IdempotencyKey)
if err != nil {
return err
}
comment.IdempotencyKey = & key
span := logIntent("comment.publish", key, comment.AuthorID, comment.VideoID)
2026-10-19 13:08:58 +08:00
2026-11-02 22:38:31 +08:00
if ok, err := s.videos.IsExist(ctx, comment.VideoID); err != nil {
return err
} else if !ok {
return fmt.Errorf("%w: video not found", apierror.ErrValidation)
}
2026-10-19 13:08:58 +08:00
2026-11-02 22:38:31 +08:00
comment.CreatedAt = time.Now().UTC()
commentEnqueued := false
if err := s.commentMQ.Publish(ctx, rabbitmq.CommentEvent{
EventID: key,
Action: "publish",
Username: comment.Username,
VideoID: comment.VideoID,
AuthorID: comment.AuthorID,
Content: comment.Content,
}); err == nil {
commentEnqueued = true
} else {
log.Printf("%s enqueue comment failed, fallback to direct write: %v", span, err)
}< / pre >
2026-10-19 13:08:58 +08:00
2026-11-02 22:38:31 +08:00
< p > 幂等约束在表上,不在代码里:< / p >
2026-10-19 13:08:58 +08:00
2026-11-02 22:38:31 +08:00
< div class = "tablewrap" >
< table >
< thead >
< tr > < th > 写入路径< / th > < th > 唯一索引< / th > < th > 重复投递的结果< / th > < / tr >
< / thead >
< tbody >
< tr > < td > 点赞< / td > < td > < code > idx_like_video_account (video_id, account_id)< / code > < / td > < td > < code > created=false< / code > ,计数与热度都不动< / td > < / tr >
< tr > < td > 评论< / td > < td > < code > uk_comments_author_key (author_id, idempotency_key)< / code > < / td > < td > < code > created=false< / code > ,不再加热度< / td > < / tr >
2026-11-12 14:15:24 +08:00
< tr > < td > 关注< / td > < td > < code > idx_social_follower_vlogger (follower_id, vlogger_id)< / code > < / td > < td > < code > ON CONFLICT DO NOTHING< / code > 挡下,< code > RowsAffected=0< / code > → < code > created=false< / code > , 200 返回< / td > < / tr >
2026-11-02 22:38:31 +08:00
< / tbody >
< / table >
< / div >
2026-10-19 13:08:58 +08:00
2026-11-02 22:38:31 +08:00
< p > 评论的索引只含 < code > author_id< / code > 与 < code > idempotency_key< / code > ,不含 < code > video_id< / code > 。这是刻意的:同一创作者用同一个 < code > request_id< / code > 重试,即使请求体里的视频被改掉,也应该被当成同一次意图挡掉。代价是客户端如果复用 < code > request_id< / code > 去评论另一个视频,会静默命中旧行——所以「每次新评论生成新 id」的责任在客户端。< / p >
2026-10-19 13:08:58 +08:00
2026-11-02 22:38:31 +08:00
< p > 删除评论也做了对称的幂等:先投 < code > comment.events< / code > 的 < code > delete< / code > ;投递失败才直写 < code > DeleteWithPopularity< / code > 。这个方法返回「被删的行 + 是否真的删掉」,< code > !ok< / code > 表示评论已经不在了,此时直接 < code > return nil< / code > , < b > 热度不能再减一次< / b > 。删除还会先查作者:不是作者本人,返回 < code > apierror.ErrUnauthorized< / code > ( 401) ; 评论不存在返回 < code > "comment not found"< / code > ( 500, 与点赞同一类问题) 。< / p >
2026-10-19 13:08:58 +08:00
< div class = "box warn" >
2026-11-02 22:38:31 +08:00
< div class = "box-t" > 评论的「已发布」与「可见」是两件事< / div >
< p > 接口返回 < code > {"message":"comment published successfully","request_id":"..."}< / code > ,它回显的是幂等键,< b > 不是评论 ID< / b > 。评论行由 Worker 稍后写入,所以发布成功后立刻拉列表可能还看不到自己那条;客户端要按 < code > request_id< / code > 做乐观占位,而不是希望接口返回一条完整评论。< / p >
2026-10-19 13:08:58 +08:00
< / div >
2026-11-02 22:38:31 +08:00
< h3 id = "sec-11-3" > < span class = "n" > 11.3< / span > 关注:反过来的 DB-first + MQ 仅通知< / h3 >
2026-10-19 13:08:58 +08:00
2026-11-02 22:38:31 +08:00
< p > 关注没有计数列、没有热度窗口。它只写一行 < code > socials< / code > ,另外让「我正在关注的人的 Feed」缓存失效。这两件事都必须同步完成, 否则用户点完关注再点进关注流, 看到的还是旧列表。于是顺序反过来: 先落库, 再失效缓存, 最后才发 MQ。< / p >
2026-10-19 13:08:58 +08:00
2026-11-12 14:15:24 +08:00
< pre data-lang = "go" > // backend/internal/social/service.go —— Follow 的顺序即语义( P1-4 之后)
if social.FollowerID == social.VloggerID {
return false, ErrCannotFollowSelf // 400, 不写库也不发通知
2026-11-02 22:38:31 +08:00
}
2026-11-12 14:15:24 +08:00
if _, err := s.accountrepo.FindByID(ctx, social.FollowerID); err != nil {
return false, err // 两个账号都必须存在
}
if _, err := s.accountrepo.FindByID(ctx, social.VloggerID); err != nil {
return false, err
}
created, err := s.repo.Follow(ctx, social) // INSERT … ON CONFLICT DO NOTHING
if err != nil {
return false, err
}
if !created {
return false, nil // 重复关注: 200 + created=false
}
s.invalidateFollowingFeedCache(context.Background(), social.FollowerID)
if err := s.socialMQ.Follow(ctx, social.FollowerID, social.VloggerID); err != nil {
2026-11-02 22:38:31 +08:00
log.Printf("social MQ Follow 发布失败: %v", err) // 只影响通知
}
2026-11-12 14:15:24 +08:00
return true, nil< / pre >
< p > < code > socialMQ.Follow< / code > 的失败只写日志,而且只有在关系< b > 真的被插入< / b > ( < code > created=true< / code > )时才发。关注关系在发消息之前就已经在 < code > SocialService< / code > 里写完了,< code > social.events< / code > 现在只有一个消费者: Worker 进程里的 < code > NotificationWorker< / code > 消费 < code > notification.social< / code > (绑定键只有 < code > social.follow< / code > ),负责写通知并经 Redis 广播到各 API 实例的 SSEHub。写库不再有第二遍——P1-4 删掉了 < code > SocialWorker< / code > 那条重放链路,所以「重复关注撞 1062 当成功 ack」的戏码也跟着消失了: 幂等由 < code > ON CONFLICT DO NOTHING< / code > 加 < code > RowsAffected< / code > 在一条 SQL 里给出结论,重复请求返回 200 + < code > created:false< / code > ,既不失效缓存也不发通知。< / p >
2026-10-19 13:08:58 +08:00
2026-11-12 14:15:24 +08:00
< p > 这仍然不改变「DB 是第一落点」: 落库已经发生, MQ 只是附加的通知路径,所以它既可以丢、也允许丢——丢掉的只是实时提醒,不是关注状态。这与点赞/评论正好相反——那两条链路里 MQ 是< b > 唯一< / b > 写路径,失败必须降级直写;关注里 MQ 是< b > 附加< / b > 路径,失败可以丢。判断标准不是「消息重不重要」,而是「消息是不是状态的唯一来源」。< / p >
2026-10-19 13:08:58 +08:00
2026-11-02 22:38:31 +08:00
< p > 缓存失效用的是通配删除:< code > feed:listByFollowing:*:accountID=< follower> :*< / code > 。只删某个 < code > limit< / code > 或某个 < code > before< / code > 的键不够——第一页变了,后面每一页的游标都跟着变。这个动作失败也只记日志,因为关注流本身还有「缓存未命中就查库」的兜底。< / p >
2026-10-19 13:08:58 +08:00
< div class = "box note" >
2026-11-02 22:38:31 +08:00
< div class = "box-t" > 取消关注没有「自关注」预检< / div >
2026-11-12 14:15:24 +08:00
< p > < code > Follow< / code > 会拦住 < code > follower == vlogger< / code > 并返回 < code > "can not follow self"< / code > ( 400) ; < code > Unfollow< / code > 不查这一条,因为自关注在库里从来不可能存在,删它只会得到 < code > deleted=false< / code > 的 200。两条路径的校验不对称, 是「按可能状态校验」而不是「按参数对称校验」。顺带一提, P1-4 之后连「是否关注过」也不再有独立的预查:< code > Follow< / code > 与 < code > Unfollow< / code > 都直接写、用 < code > RowsAffected< / code > 判断这次有没有真变更,重复调用返回 < code > created:false< / code > / < code > deleted:false< / code > ,不再有 1062 或「not followed」这类错误码需要翻译。< / p >
2026-10-19 13:08:58 +08:00
< / div >
2026-11-02 22:38:31 +08:00
< h3 id = "sec-11-4" > < span class = "n" > 11.4< / span > 降级矩阵: MQ 或 Redis 挂掉会发生什么< / h3 >
2026-10-19 13:08:58 +08:00
2026-11-02 22:38:31 +08:00
< p > 降级不是「catch 住异常继续跑」,而是每一种依赖缺失时都有一条事先写好的替代路径。三条写路径共用同一个 MQ 连接管理器,所以它们的降级触发点是同一个:< code > PublishJSON → Session → WaitReady< / code > 。< / p >
2026-10-19 13:08:58 +08:00
2026-11-02 22:38:31 +08:00
< pre data-lang = "go" > // backend/internal/middleware/rabbitmq/rabbitMQ.go —— WaitReady 的等待语义
if r == nil {
return errors.New("rabbitmq manager is nil") // 未启用 MQ: 立即失败
2026-10-19 13:08:58 +08:00
}
2026-11-03 00:14:23 +08:00
for {
r.mu.Lock()
ready := r.ready
conn := r.conn
r.mu.Unlock()
if conn != nil & & !conn.IsClosed() {
return nil // 连接可用:立刻放行
}
2026-11-02 22:38:31 +08:00
select {
2026-11-03 00:14:23 +08:00
case < -ready: // 代际变化:回到循环顶部重新判定
case < -r.closed: // 管理器已关闭
return ErrManagerClosed
case < -ctx.Done(): // 请求超时/取消
2026-11-02 22:38:31 +08:00
return ctx.Err()
}
2026-11-03 00:14:23 +08:00
}< / pre >
< p > < code > ready< / code > 只是唤醒信号,不是就绪信号——这正是外层 < code > for< / code > 存在的理由。断连(< code > markDown< / code > )与重连(< code > install< / code > )都会关掉旧的 < code > ready< / code > 再换一个新的,被唤醒的发布方必须回到循环顶部重读一次 < code > conn< / code > ,只有它真的可用才 < code > return nil< / code > 。所以断连期间发布既不空转轮询,也不会误判就绪,就一直停在 < code > select< / code > 上。< / p >
2026-10-19 13:08:58 +08:00
< div class = "tablewrap" >
2026-11-02 22:38:31 +08:00
< table >
< thead >
< tr > < th > 故障< / th > < th > 点赞< / th > < th > 评论< / th > < th > 关注< / th > < / tr >
< / thead >
< tbody >
< tr > < td > MQ 未启用(< code > rmq == nil< / code > ) < / td > < td > publisher 为 nil, 直接走事务直写 + 本进程热度< / td > < td > 同上,直写评论行并加热度< / td > < td > 关注成立,通知丢失(日志)< / td > < / tr >
< tr > < td > MQ 断开< / td > < td > 发布阻塞至请求 < code > ctx< / code > 取消,然后降级直写< / td > < td > 同上< / td > < td > 关注已落库,通知丢失< / td > < / tr >
< tr > < td > Redis 不可用< / td > < td > 写路径不受影响;< code > ApplyHotDelta< / code > 报错只记日志,热度窗口暂时缺失< / td > < td > 同左< / td > < td > 缓存失效失败只记日志;关注流退回查库< / td > < / tr >
< tr > < td > Redis 锁不可用< / td > < td > 不涉及< / td > < td > 不涉及< / td > < td > 不涉及; Feed 读路径拿不到锁就直查 DB< / td > < / tr >
< tr > < td > Worker 未运行< / td > < td > 消息堆积;列表看得到旧计数,热度不动< / td > < td > 评论不可见,直到 Worker 消费< / td > < td > 关注立即可见( DB-first) , 但通知不来< / td > < / tr >
< / tbody >
< / table >
2026-10-19 13:08:58 +08:00
< / div >
2026-11-03 00:14:23 +08:00
< p > 这张表解释了一个常被问的问题: MQ 挂了为什么接口还能成功?因为「投递失败」在代码里不是错误,而是< b > 降级信号< / b > 。断连期间 < code > PublishJSON< / code > 会一直阻塞在 < code > WaitReady< / code > ,直到请求 < code > ctx< / code > 取消才带着 < code > ctx.Err()< / code > 返回,调用方随即转入直写分支;只有当 < code > ctx< / code > 已经取消、连数据库写也做不了时,返回的才是 5xx。< / p >
2026-10-19 13:08:58 +08:00
2026-11-12 14:15:24 +08:00
< h3 id = "sec-11-5" > < span class = "n" > 11.5< / span > 两个 Worker 的落库逻辑与计数副作用< / h3 >
2026-10-19 13:08:58 +08:00
2026-11-12 14:15:24 +08:00
< p > Worker 侧判断「这次没改变状态」有两种写法。点赞与评论的仓储返回布尔量:< code > ApplyLike< / code > 的 < code > created< / code > 、< code > CreateIdempotentWithPopularity< / code > 的第一个返回值,< code > false< / code > 表示这条消息是重复投递。关注已经不走 Worker: < code > SocialService.Follow< / code > 在 API 进程里直接调 < code > repo.Follow< / code > ,拿它的 < code > RowsAffected< / code > 当布尔量,< code > ON CONFLICT DO NOTHING< / code > 挡住了并发插入,不需要再读 1062。两条路最后都安静地 < code > return nil< / code > (即 ack) 。把「重复」与「失败」分开, 重试才不会放大副作用。< / p >
2026-10-19 13:08:58 +08:00
< div class = "tablewrap" >
2026-11-02 22:38:31 +08:00
< table >
< thead >
< tr > < th > Worker< / th > < th > 幂等依据< / th > < th > 一次成功的副作用< / th > < th > 重复投递时< / th > < / tr >
< / thead >
< tbody >
< tr > < td > < code > LikeWorker< / code > < / td > < td > < code > idx_like_video_account< / code > < / td > < td > 插点赞行、< code > likes_count+1< / code > 、< code > popularity+1< / code > 、窗口 < code > +1< / code > < / td > < td > < code > created=false< / code > → ack, 不加热度< / td > < / tr >
< tr > < td > < code > CommentWorker< / code > < / td > < td > < code > uk_comments_author_key< / code > ,键取消息里的 < code > event_id< / code > < / td > < td > 插评论行、< code > popularity+1< / code > 、窗口 < code > +1< / code > < / td > < td > < code > created=false< / code > → 日志 < code > dedupe=hit< / code > , ack< / td > < / tr >
< / tbody >
< / table >
2026-10-19 13:08:58 +08:00
< / div >
2026-11-02 22:38:31 +08:00
< p > 评论的幂等键必须是消息里的 < code > event_id< / code > ,因为 API 直写与 Worker 消费可能同时发生: API 走降级分支插入时用的也是同一个键,谁先到谁插入,后到的那个被唯一索引挡掉,< code > created=false< / code > ,热度只加一次。这就是「事件 ID 即意图键」的用法——同一意图在两条路径上共享一个去重标识。< / p >
2026-10-19 13:08:58 +08:00
2026-11-02 22:38:31 +08:00
< pre data-lang = "go" > // backend/internal/video/comment_repo.go —— 行与热度同事务
res := tx.Clauses(clause.OnConflict{DoNothing: true}).Create(c)
if res.RowsAffected == 0 {
return false, nil // 该意图已落库
}
tx.Model(& Video{}).Where("id = ?", c.VideoID).
UpdateColumn("popularity", gorm.Expr("GREATEST(popularity + ?, 0)", delta))< / pre >
2026-10-19 13:08:58 +08:00
2026-11-02 22:38:31 +08:00
< p > 行与 < code > popularity< / code > 在同一个事务里,所以不存在「评论进去了、计数没加」的中间态。真正可能落后的是< b > 热度窗口< / b > :它在事务提交之后由 < code > ApplyHotDelta< / code > 单独写,失败只记日志。这是刻意的取舍——窗口是派生数据,< code > -rebuild-hot< / code > 能从库里重建,不值得为它回滚一条已经成立的评论。< / p >
2026-10-19 13:08:58 +08:00
2026-11-02 22:38:31 +08:00
< h3 id = "sec-11-6" > < span class = "n" > 11.6< / span > 提及通知:唯一绕过 MQ 的写入路径< / h3 >
2026-10-19 13:08:58 +08:00
2026-11-02 22:38:31 +08:00
< p > 评论里的 < code > @某人< / code > 不走 MQ。它在 < code > Publish< / code > 的最后一步同步解析、同步写 < code > notifications< / code > 表,用的是批量插入 + < code > ON CONFLICT DO NOTHING< / code > ,去重键为 < code > NotificationDedupeKey("mention", intentKey, recipientID)< / code > 。键里带收件人,因为同一条评论可能提及多个人。< / p >
2026-10-19 13:08:58 +08:00
2026-11-02 22:38:31 +08:00
< pre data-lang = "go" > // backend/internal/video/comment_service.go —— notifyMentions 的落库片段
rows = append(rows, notification.Notification{
RecipientID: m.RecipientID,
SenderID: m.SenderID,
Type: "mention",
TargetID: m.TargetID,
Content: m.Content,
CreatedAt: now,
DedupeKey: nilIfEmpty(m.DedupeKey),
})
return r.db.WithContext(ctx).
Clauses(clause.OnConflict{DoNothing: true}).
Create(& rows).Error< / pre >
2026-10-19 13:08:58 +08:00
2026-11-02 22:38:31 +08:00
< p > 三个细节值得记住。第一,正则只有 < code > @(\w+)< / code > :中文昵称、带点或连字符的用户名不会被识别,这是已知限制。第二,解析完会跳过发起者自己,并按用户名去重,避免同一条评论里重复 < code > @< / code > 同一个人写多行。第三,通知是< b > 派生副作用< / b > : < code > CreateMentions< / code > 失败只写 < code > stage=mention.create< / code > 日志,不影响「评论已发布」的返回。< / p >
2026-10-19 13:08:58 +08:00
< div class = "box warn" >
2026-11-02 22:38:31 +08:00
< div class = "box-t" > 提及通知不推 SSE< / div >
< p > < code > notifications< / code > 行写进去了,但没有调用 < code > SSEHub.Push< / code > 。在线用户要等下一次 < code > /notification/list< / code > 轮询或重新打开页面才能看到提及;点赞/评论/关注的通知则会在 Worker 插入成功后实时推送。这是两条不同的通知入口,行为并不一致。< / p >
2026-10-19 13:08:58 +08:00
< / div >
2026-11-02 22:38:31 +08:00
< h3 id = "sec-11-7" > < span class = "n" > 11.7< / span > 读不到自己的写:异步一致性的用户体验< / h3 >
< p > 三条路径的「可见时间」不同,前端必须按动作分别处理,而不能假设「接口 200 就等于所有视图都更新了」。< / p >
2026-10-19 13:08:58 +08:00
< div class = "tablewrap" >
2026-11-02 22:38:31 +08:00
< table >
< thead >
< tr > < th > 动作< / th > < th > 什么时候可见< / th > < th > 前端应该怎么做< / th > < / tr >
< / thead >
< tbody >
< tr > < td > 点赞 / 取消点赞< / td > < td > 点赞状态要等 Worker 落库;列表计数更晚< / td > < td > 本地先翻转按钮,列表数字等下一次拉取< / td > < / tr >
< tr > < td > 评论发布< / td > < td > Worker 落库后才出现在列表< / td > < td > 用 < code > request_id< / code > 占位,重复提交不产生第二条< / td > < / tr >
< tr > < td > 关注< / td > < td > 立即可见( DB-first) , 关注流缓存同时失效< / td > < td > 直接刷新关注按钮与关注流< / td > < / tr >
< tr > < td > 通知< / td > < td > Worker 消费后插入, SSE 在线才实时< / td > < td > 打开页面先拉一次 < code > /notification/list< / code > < / td > < / tr >
< / tbody >
< / table >
2026-10-19 13:08:58 +08:00
< / div >
2026-11-03 13:07:55 +08:00
< p > 这也是 < code > POST /video/getDetail< / code > 的计数可能比列表「新」或「旧」的原因:详情走 < code > video:detail< / code > 缓存( 5 分钟)并在热度变更时被删除,列表走各自的查询与缓存。两个视图没有共享同一份读快照,所以数字短暂不一致是正常现象,不是数据损坏。< / p >
2026-10-19 13:08:58 +08:00
< div class = "box ok" >
2026-11-02 22:38:31 +08:00
< div class = "box-t" > 本章结论速记< / div >
< ul >
< li > MQ-first 的判据是「消息是不是状态的唯一写路径」:点赞、评论是;关注不是。< / li >
< li > 点赞的幂等键是唯一索引,< code > intent_key< / code > 只进日志;评论的幂等键是客户端 < code > request_id< / code > 。< / li >
< li > 重复投递的正确反应是 < code > created=false → ack< / code > ,不是报错,也不是重新加热度。< / li >
< li > 计数与行同事务;热度窗口在提交后 best-effort, 可重建。< / li >
< li > 降级不是兜底异常,而是每个依赖缺失时都有一条写好的替代路径。< / li >
< li > 「接口 200」只代表动作被接收, 可见性各自不同。< / li >
< / ul >
2026-10-19 13:08:58 +08:00
< / 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 >