refactor(worker): 删除冗余的 SocialWorker
服务层已经写库。SocialWorker 再写一次是重复。因此删除它。 cmd/worker 不再构造 social 仓储,也不再声明 social 主队列拓扑。 验证:go build ./... 通过,go test -count=1 ./internal/worker/... 全绿。
This commit is contained in:
@@ -1,70 +0,0 @@
|
||||
package worker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"feedsystem_video_go/internal/middleware/rabbitmq"
|
||||
"feedsystem_video_go/internal/social"
|
||||
|
||||
"github.com/go-sql-driver/mysql"
|
||||
amqp "github.com/rabbitmq/amqp091-go"
|
||||
)
|
||||
|
||||
type SocialWorker struct {
|
||||
ch *amqp.Channel
|
||||
parker rabbitmq.Parker
|
||||
repo *social.SocialRepository
|
||||
queue string
|
||||
}
|
||||
|
||||
func NewSocialWorker(ch *amqp.Channel, parker rabbitmq.Parker, repo *social.SocialRepository, queue string) *SocialWorker {
|
||||
return &SocialWorker{ch: ch, parker: parker, repo: repo, queue: queue}
|
||||
}
|
||||
|
||||
func (w *SocialWorker) Run(ctx context.Context) error {
|
||||
if w == nil || w.ch == nil || w.repo == nil {
|
||||
return errors.New("social worker is not initialized")
|
||||
}
|
||||
if w.queue == "" {
|
||||
return errors.New("queue is required")
|
||||
}
|
||||
return rabbitmq.ConsumeLoop(ctx, w.ch, w.parker, w.queue, rabbitmq.MaxAttempts, w.process)
|
||||
}
|
||||
|
||||
func (w *SocialWorker) process(ctx context.Context, d amqp.Delivery) error {
|
||||
var evt rabbitmq.SocialEvent
|
||||
if err := json.Unmarshal(d.Body, &evt); err != nil {
|
||||
return rabbitmq.Permanent(fmt.Errorf("social worker: decode event: %w", err))
|
||||
}
|
||||
if evt.FollowerID == 0 || evt.VloggerID == 0 {
|
||||
return rabbitmq.Permanent(fmt.Errorf("social worker: invalid event follower_id=%d vlogger_id=%d", evt.FollowerID, evt.VloggerID))
|
||||
}
|
||||
|
||||
switch evt.Action {
|
||||
case "follow":
|
||||
_, err := w.repo.Follow(ctx, &social.Social{
|
||||
FollowerID: evt.FollowerID,
|
||||
VloggerID: evt.VloggerID,
|
||||
})
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
// 重复投递:关注关系已在,唯一索引挡下第二条。这是成功语义。
|
||||
var mysqlErr *mysql.MySQLError
|
||||
if errors.As(err, &mysqlErr) && mysqlErr.Number == 1062 {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
case "unfollow":
|
||||
_, err := w.repo.Unfollow(ctx, &social.Social{
|
||||
FollowerID: evt.FollowerID,
|
||||
VloggerID: evt.VloggerID,
|
||||
})
|
||||
return err
|
||||
default:
|
||||
return rabbitmq.Permanent(fmt.Errorf("social worker: unknown action %q", evt.Action))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user