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

70 lines
1.9 KiB
Go
Raw Normal View History

2025-12-30 01:25:54 +08:00
package rabbitmq
import (
"context"
"errors"
"time"
)
// CommentMQ 通过连接管理器发布评论事件(不再持有长生命周期 channel)。
2025-12-30 01:25:54 +08:00
type CommentMQ struct {
mgr *RabbitMQ
2025-12-30 01:25:54 +08:00
}
const (
commentExchange = "comment.events"
commentQueue = "comment.events"
commentBindingKey = "comment.*"
commentPublishRK = "comment.publish"
commentDeleteRK = "comment.delete"
)
type CommentEvent struct {
EventID string `json:"event_id"`
Action string `json:"action"`
CommentID uint `json:"comment_id,omitempty"`
Username string `json:"username,omitempty"`
VideoID uint `json:"video_id,omitempty"`
AuthorID uint `json:"author_id,omitempty"`
Content string `json:"content,omitempty"`
OccurredAt time.Time `json:"occurred_at"`
}
func NewCommentMQ(base *RabbitMQ) (*CommentMQ, error) {
if base == nil {
return nil, errors.New("rabbitmq base is nil")
}
base.RegisterTopology(Topology{Exchange: commentExchange, Queue: commentQueue, BindingKey: commentBindingKey})
return &CommentMQ{mgr: base}, nil
2025-12-30 01:25:54 +08:00
}
func (c *CommentMQ) Publish(ctx context.Context, username string, videoID, authorID uint, content string) error {
return c.publish(ctx, "publish", commentPublishRK, CommentEvent{
Username: username,
VideoID: videoID,
AuthorID: authorID,
Content: content,
})
}
func (c *CommentMQ) Delete(ctx context.Context, commentID uint) error {
return c.publish(ctx, "delete", commentDeleteRK, CommentEvent{
CommentID: commentID,
})
}
func (c *CommentMQ) publish(ctx context.Context, action, routingKey string, evt CommentEvent) error {
if c == nil || c.mgr == nil {
2025-12-30 01:25:54 +08:00
return errors.New("comment mq is not initialized")
}
id, err := newEventID(16)
if err != nil {
return err
}
evt.EventID = id
evt.Action = action
evt.OccurredAt = time.Now().UTC()
return c.mgr.PublishJSON(ctx, commentExchange, routingKey, evt)
2025-12-30 01:25:54 +08:00
}