69 lines
1.8 KiB
Go
69 lines
1.8 KiB
Go
package rabbitmq
|
||
|
||
import (
|
||
"context"
|
||
"errors"
|
||
"time"
|
||
)
|
||
|
||
// CommentMQ 通过连接管理器发布评论事件。
|
||
type CommentMQ struct {
|
||
mgr *RabbitMQ
|
||
}
|
||
|
||
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
|
||
}
|
||
|
||
// Publish 接收完整事件;EventID 由调用方生成,仅为空时补一个随机值。
|
||
func (c *CommentMQ) Publish(ctx context.Context, evt CommentEvent) error {
|
||
return c.publish(ctx, "publish", CommentPublishRK, evt)
|
||
}
|
||
|
||
func (c *CommentMQ) Delete(ctx context.Context, commentID uint, intentKey string) error {
|
||
return c.publish(ctx, "delete", CommentDeleteRK, CommentEvent{
|
||
CommentID: commentID,
|
||
EventID: intentKey,
|
||
})
|
||
}
|
||
|
||
func (c *CommentMQ) publish(ctx context.Context, action, routingKey string, evt CommentEvent) error {
|
||
if c == nil || c.mgr == nil {
|
||
return errors.New("comment mq is not initialized")
|
||
}
|
||
if evt.EventID == "" {
|
||
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)
|
||
}
|