点赞与评论的计数只由业务事务写。ApplyLike、ApplyUnlike、CreateIdempotentWithPopularity 与 DeleteWithPopularity 各自在单事务内完成插行与计数。 热榜增量改为提交后的 best-effort 写。ApplyHotDelta 按行的 created_at 落分钟桶,写失败只记日志,DB 计数仍然正确。 删除 PopularityMQ 与 PopularityWorker。同一次互动因此只有一个写者,不再有两个门闩各自放行。 删除 hot:applied 占位键。判重改由 likes 的唯一索引与 uk_comments_author_key 负责。 DeleteWithPopularity 先读行再删行。评论删除因此回退热度,重复投递不再多减一次。 likes 与 comments 各加 (created_at, video_id) 覆盖索引,服务热榜窗口查询。 验证:go build -buildvcs=false ./... 通过。go test -buildvcs=false -count=1 ./... 全绿。
77 lines
2.3 KiB
Go
77 lines
2.3 KiB
Go
package rabbitmq
|
||
|
||
import (
|
||
"context"
|
||
"errors"
|
||
"time"
|
||
)
|
||
|
||
// LikeMQ 通过连接管理器发布点赞事件。
|
||
// 它不再持有长生命周期 channel——连接断开后由管理器重建,发布自动恢复。
|
||
type LikeMQ struct {
|
||
mgr *RabbitMQ
|
||
}
|
||
|
||
// 拓扑常量导出:交换机名 / 队列名 / 绑定键是跨进程的"线缆契约",
|
||
// cmd/worker 与 http 层登记拓扑时必须复用同一份定义,不能再各自写字符串字面量。
|
||
const (
|
||
LikeExchange = "like.events"
|
||
LikeQueue = "like.events"
|
||
LikeBindingKey = "like.*"
|
||
|
||
LikeLikeRK = "like.like" // 点赞路由键
|
||
LikeUnlikeRK = "like.unlike" // 取消点赞路由键
|
||
)
|
||
|
||
type LikeEvent struct {
|
||
EventID string `json:"event_id"`
|
||
Action string `json:"action"`
|
||
UserID uint `json:"user_id"`
|
||
VideoID uint `json:"video_id"`
|
||
OccurredAt time.Time `json:"occurred_at"`
|
||
}
|
||
|
||
func NewLikeMQ(base *RabbitMQ) (*LikeMQ, error) {
|
||
if base == nil {
|
||
return nil, errors.New("rabbitmq base is nil")
|
||
}
|
||
// 拓扑交给管理器登记:每一代连接都会自动重放,不再只声明一次
|
||
base.RegisterTopology(Topology{Exchange: LikeExchange, Queue: LikeQueue, BindingKey: LikeBindingKey})
|
||
return &LikeMQ{mgr: base}, nil
|
||
}
|
||
|
||
// Like / Unlike 的 intentKey 只作为 LikeEvent.EventID:调用方用它把日志与
|
||
// 一条用户意图对齐,判重仍由 likes 表的唯一索引负责(见 ApplyLike)。
|
||
func (l *LikeMQ) Like(ctx context.Context, userID, videoID uint, intentKey string) error {
|
||
return l.publish(ctx, "like", LikeLikeRK, userID, videoID, intentKey)
|
||
}
|
||
|
||
func (l *LikeMQ) Unlike(ctx context.Context, userID, videoID uint, intentKey string) error {
|
||
return l.publish(ctx, "unlike", LikeUnlikeRK, userID, videoID, intentKey)
|
||
}
|
||
|
||
func (l *LikeMQ) publish(ctx context.Context, action, routingKey string, userID, videoID uint, intentKey string) error {
|
||
if l == nil || l.mgr == nil {
|
||
return errors.New("like mq is not initialized")
|
||
}
|
||
if userID == 0 || videoID == 0 {
|
||
return errors.New("userID and videoID are required")
|
||
}
|
||
id := intentKey
|
||
if id == "" {
|
||
var err error
|
||
id, err = newEventID(16)
|
||
if err != nil {
|
||
return err
|
||
}
|
||
}
|
||
event := LikeEvent{
|
||
EventID: id,
|
||
Action: action,
|
||
UserID: userID,
|
||
VideoID: videoID,
|
||
OccurredAt: time.Now(),
|
||
}
|
||
return l.mgr.PublishJSON(ctx, LikeExchange, routingKey, event)
|
||
}
|