2025-10-11 14:56:11 +08:00
|
|
|
package data
|
2025-10-23 18:02:29 +08:00
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"context"
|
|
|
|
|
"datart/data/rabbit"
|
|
|
|
|
"datart/log"
|
2025-11-20 20:58:51 +08:00
|
|
|
"encoding/json"
|
|
|
|
|
"errors"
|
2025-10-23 18:02:29 +08:00
|
|
|
"fmt"
|
|
|
|
|
|
|
|
|
|
rmq "github.com/rabbitmq/rabbitmq-amqp-go-client/pkg/rabbitmqamqp"
|
|
|
|
|
)
|
|
|
|
|
|
2025-11-20 20:58:51 +08:00
|
|
|
var eventNotifyXQK = rabbit.XQK{
|
|
|
|
|
Exchange: "event_notify_fanout",
|
2025-10-23 18:02:29 +08:00
|
|
|
}
|
|
|
|
|
|
2025-11-20 20:58:51 +08:00
|
|
|
var eventNotifyPublisher *rmq.Publisher
|
2025-10-23 18:02:29 +08:00
|
|
|
|
|
|
|
|
func init() {
|
2025-11-20 20:58:51 +08:00
|
|
|
ctx := context.Background()
|
|
|
|
|
|
|
|
|
|
m := new(rabbit.Manage)
|
|
|
|
|
|
|
|
|
|
rm := rabbit.DefaultManagement()
|
|
|
|
|
|
|
|
|
|
rx := &rmq.FanOutExchangeSpecification{
|
|
|
|
|
Name: eventNotifyXQK.Exchange,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
m.Init(ctx, rm, rx, nil, nil)
|
|
|
|
|
|
|
|
|
|
m.DeclareExchange(ctx)
|
|
|
|
|
|
|
|
|
|
publisher, err := rabbit.NewPublisher(ctx, "default", &eventNotifyXQK)
|
2025-10-23 18:02:29 +08:00
|
|
|
if err != nil {
|
|
|
|
|
panic(err)
|
|
|
|
|
}
|
2025-11-20 20:58:51 +08:00
|
|
|
eventNotifyPublisher = publisher
|
2025-10-23 18:02:29 +08:00
|
|
|
}
|
|
|
|
|
|
2025-11-20 20:58:51 +08:00
|
|
|
func PublishEvent(ctx context.Context, event any) error {
|
|
|
|
|
data, err := json.Marshal(event)
|
2025-10-23 18:02:29 +08:00
|
|
|
if err != nil {
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
|
2025-11-20 20:58:51 +08:00
|
|
|
result, err := eventNotifyPublisher.Publish(ctx, rmq.NewMessage(data))
|
2025-10-23 18:02:29 +08:00
|
|
|
if err != nil {
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
switch result.Outcome.(type) {
|
|
|
|
|
case *rmq.StateAccepted:
|
2025-11-20 20:58:51 +08:00
|
|
|
// "message accepted"
|
2025-10-23 18:02:29 +08:00
|
|
|
case *rmq.StateReleased:
|
2025-11-20 20:58:51 +08:00
|
|
|
// "message released"
|
2025-10-23 18:02:29 +08:00
|
|
|
case *rmq.StateRejected:
|
2025-11-20 20:58:51 +08:00
|
|
|
return errors.New("message rejected")
|
2025-10-23 18:02:29 +08:00
|
|
|
default:
|
2025-11-20 20:58:51 +08:00
|
|
|
return fmt.Errorf("invalid message state: %v", result.Outcome)
|
2025-10-23 18:02:29 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func CloseEventPublisher(ctx context.Context) {
|
2025-11-20 20:58:51 +08:00
|
|
|
if err := eventNotifyPublisher.Close(ctx); err != nil {
|
2025-10-23 18:02:29 +08:00
|
|
|
log.Error(err)
|
|
|
|
|
}
|
|
|
|
|
}
|