LikeMQ / CommentMQ / SocialMQ / PopularityMQ / TimelineMQ 原先各自在构造时取一个 *amqp.Channel 并终身持有,连接断开后发布持续失败,而 API 进程没有任何重建逻辑 (即报告 P1-13):业务数据因 DB 直写降级仍然正确,但通知、热度、时间线全部静默 停更,且不会自愈——只修消费者会得到一个"消费者活着、消息却不再产生"的半自愈系统。 改为:各 publisher 只持 *RabbitMQ,构造时用 RegisterTopology 登记拓扑(不再 "构造时声明一次"),发布统一走 mgr.PublishJSON;管理器内部为每一代连接复用一个 发布 channel,发布失败即丢弃缓存、随下一代重建。amqp091-go 的 Publish 内部持锁, 多 goroutine 复用同一 channel 是安全的(只是串行化)。 刻意不做"ErrClosed 时自动重发":那会在 P0-4 的双写窗口之上再叠加一次不确定性。 发布失败如实返回错误,交由既有的 DB 直写降级路径,幂等应交给事件层(event_id)。 各 NewXxxMQ 的签名保持不变,router.go 的 5 个构造点无需改动。同时删除上一个提交 为兼容尚未迁移的 publisher 而临时保留的包级 PublishJSON。
69 lines
1.8 KiB
Go
69 lines
1.8 KiB
Go
package rabbitmq
|
||
|
||
import (
|
||
"context"
|
||
"errors"
|
||
"time"
|
||
)
|
||
|
||
// LikeMQ 通过连接管理器发布点赞事件。
|
||
// 它不再持有长生命周期 channel——连接断开后由管理器重建,发布自动恢复。
|
||
type LikeMQ struct {
|
||
mgr *RabbitMQ
|
||
}
|
||
|
||
const (
|
||
likeExchange = "like.events"
|
||
likeQueue = "like.events"
|
||
likeBindingKey = "like.*"
|
||
|
||
likeLikeRK = "like.like" // 点赞路由键
|
||
likeUnlikeRK = "like.unlike" // 取消点赞路由键
|
||
)
|
||
|
||
type LikeEvent struct {
|
||
EventID string `json:"event_id"`
|
||
Action string `json:"action"`
|
||
UserID uint `json:"user_id"`
|
||
VideoID uint `json:"video_id"`
|
||
OccurredAt time.Time `json:"occurred_at"`
|
||
}
|
||
|
||
func NewLikeMQ(base *RabbitMQ) (*LikeMQ, error) {
|
||
if base == nil {
|
||
return nil, errors.New("rabbitmq base is nil")
|
||
}
|
||
// 拓扑交给管理器登记:每一代连接都会自动重放,不再只声明一次
|
||
base.RegisterTopology(Topology{Exchange: likeExchange, Queue: likeQueue, BindingKey: likeBindingKey})
|
||
return &LikeMQ{mgr: base}, nil
|
||
}
|
||
|
||
func (l *LikeMQ) Like(ctx context.Context, userID, videoID uint) error {
|
||
return l.publish(ctx, "like", likeLikeRK, userID, videoID)
|
||
}
|
||
|
||
func (l *LikeMQ) Unlike(ctx context.Context, userID, videoID uint) error {
|
||
return l.publish(ctx, "unlike", likeUnlikeRK, userID, videoID)
|
||
}
|
||
|
||
func (l *LikeMQ) publish(ctx context.Context, action, routingKey string, userID, videoID uint) error {
|
||
if l == nil || l.mgr == nil {
|
||
return errors.New("like mq is not initialized")
|
||
}
|
||
if userID == 0 || videoID == 0 {
|
||
return errors.New("userID and videoID are required")
|
||
}
|
||
id, err := newEventID(16)
|
||
if err != nil {
|
||
return err
|
||
}
|
||
event := LikeEvent{
|
||
EventID: id,
|
||
Action: action,
|
||
UserID: userID,
|
||
VideoID: videoID,
|
||
OccurredAt: time.Now(),
|
||
}
|
||
return l.mgr.PublishJSON(ctx, likeExchange, routingKey, event)
|
||
}
|