feat(broker): lab5 implement publish with publisher confirms

This commit is contained in:
Голиков Maximillian Антон
2026-11-07 15:25:45 +03:00
parent 2934d221d7
commit 2048203173
+29
View File
@@ -3,6 +3,7 @@ package broker
import (
"context"
"fmt"
"time"
amqp "github.com/rabbitmq/amqp091-go"
)
@@ -39,6 +40,11 @@ func (p *RabbitPublisher) connect() error {
return fmt.Errorf("открытие канала rabbitmq: %w", err)
}
if err := p.ch.Confirm(false); err != nil {
return fmt.Errorf("включение режима confirm: %w", err)
}
p.confirms = p.ch.NotifyPublish(make(chan amqp.Confirmation, 1))
err = p.ch.ExchangeDeclare("attachments", "direct", true, false, false, false, nil)
if err != nil {
return fmt.Errorf("объявление exchange: %w", err)
@@ -56,3 +62,26 @@ func (p *RabbitPublisher) connect() error {
return nil
}
func (p *RabbitPublisher) Publish(ctx context.Context, routingKey string, body []byte) error {
err := p.ch.PublishWithContext(ctx, "attachments", routingKey, false, false, amqp.Publishing{
ContentType: "application/json",
DeliveryMode: amqp.Persistent,
Body: body,
})
if err != nil {
return err
}
select {
case confirm := <-p.confirms:
if !confirm.Ack {
return fmt.Errorf("сообщение отклонено брокером")
}
return nil
case <-time.After(5 * time.Second):
return fmt.Errorf("таймаут ожидания подтверждения от rabbitmq")
case <-ctx.Done():
return ctx.Err()
}
}