feat(broker): lab5 make publisher thread-safe with reconnect and close

This commit is contained in:
Голиков Maximillian Антон
2026-11-07 15:43:22 +03:00
parent 2048203173
commit 4413c43eb5
+23
View File
@@ -3,6 +3,7 @@ package broker
import (
"context"
"fmt"
"sync"
"time"
amqp "github.com/rabbitmq/amqp091-go"
@@ -15,6 +16,7 @@ type Publisher interface {
type RabbitPublisher struct {
url string
mu sync.Mutex
conn *amqp.Connection
ch *amqp.Channel
confirms chan amqp.Confirmation
@@ -64,6 +66,15 @@ func (p *RabbitPublisher) connect() error {
}
func (p *RabbitPublisher) Publish(ctx context.Context, routingKey string, body []byte) error {
p.mu.Lock()
defer p.mu.Unlock()
if p.conn == nil || p.conn.IsClosed() {
if err := p.connect(); err != nil {
return err
}
}
err := p.ch.PublishWithContext(ctx, "attachments", routingKey, false, false, amqp.Publishing{
ContentType: "application/json",
DeliveryMode: amqp.Persistent,
@@ -85,3 +96,15 @@ func (p *RabbitPublisher) Publish(ctx context.Context, routingKey string, body [
return ctx.Err()
}
}
func (p *RabbitPublisher) Close() error {
p.mu.Lock()
defer p.mu.Unlock()
if p.ch != nil {
_ = p.ch.Close()
}
if p.conn != nil {
return p.conn.Close()
}
return nil
}