Files
VLoop/backend/internal/middleware/rabbitmq/popularityMQ.go

67 lines
1.9 KiB
Go
Raw Normal View History

2025-12-30 01:25:30 +08:00
package rabbitmq
import (
"context"
"errors"
"time"
)
// PopularityMQ 通过连接管理器发布热度事件(不再持有长生命周期 channel)。
2025-12-30 01:25:30 +08:00
type PopularityMQ struct {
mgr *RabbitMQ
2025-12-30 01:25:30 +08:00
}
// 拓扑常量导出:见 likeMQ.go 中的说明。
2025-12-30 01:25:30 +08:00
const (
PopularityExchange = "video.popularity.events"
PopularityQueue = "video.popularity.events"
PopularityBindingKey = "video.popularity.*"
2025-12-30 01:25:30 +08:00
PopularityUpdateRK = "video.popularity.update"
2025-12-30 01:25:30 +08:00
)
type PopularityEvent struct {
EventID string `json:"event_id"`
VideoID uint `json:"video_id"`
Change int64 `json:"change"`
OccurredAt time.Time `json:"occurred_at"`
}
func NewPopularityMQ(base *RabbitMQ) (*PopularityMQ, error) {
if base == nil {
return nil, errors.New("rabbitmq base is nil")
}
base.RegisterTopology(Topology{Exchange: PopularityExchange, Queue: PopularityQueue, BindingKey: PopularityBindingKey})
return &PopularityMQ{mgr: base}, nil
2025-12-30 01:25:30 +08:00
}
// Update 发布一条热度事件。
//
// intentKey 是"这次用户意图"的稳定标识,会写进 event_id:调用方(如点赞)
// 用同一个键同时发布点赞事件与热度事件,于是两条消息无论重复投递多少次,
// 消费端都能认出"这是同一次意图"(P0-4)。intentKey 为空时退化为随机 id
// ——注意此时消费端无法去重,所以生产路径必须传键。
func (p *PopularityMQ) Update(ctx context.Context, videoID uint, change int64, intentKey string) error {
if p == nil || p.mgr == nil {
2025-12-30 01:25:30 +08:00
return errors.New("popularity mq is not initialized")
}
if videoID == 0 || change == 0 {
return errors.New("videoID and change are required")
}
id := intentKey
if id == "" {
var err error
id, err = newEventID(16)
if err != nil {
return err
}
2025-12-30 01:25:30 +08:00
}
event := PopularityEvent{
EventID: id,
VideoID: videoID,
Change: change,
OccurredAt: time.Now().UTC(),
}
return p.mgr.PublishJSON(ctx, PopularityExchange, PopularityUpdateRK, event)
2025-12-30 01:25:30 +08:00
}