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

57 lines
1.5 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
}
func (p *PopularityMQ) Update(ctx context.Context, videoID uint, change int64) 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, 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)
2025-12-30 01:25:30 +08:00
}