package rabbitmq import ( "context" "errors" "time" ) // PopularityMQ 通过连接管理器发布热度事件(不再持有长生命周期 channel)。 type PopularityMQ struct { mgr *RabbitMQ } // 拓扑常量导出:见 likeMQ.go 中的说明。 const ( PopularityExchange = "video.popularity.events" PopularityQueue = "video.popularity.events" PopularityBindingKey = "video.popularity.*" PopularityUpdateRK = "video.popularity.update" ) 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 } // 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 { 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 } } event := PopularityEvent{ EventID: id, VideoID: videoID, Change: change, OccurredAt: time.Now().UTC(), } return p.mgr.PublishJSON(ctx, PopularityExchange, PopularityUpdateRK, event) }