feat(broker): lab5 make publisher thread-safe with reconnect and close
This commit is contained in:
@@ -3,6 +3,7 @@ package broker
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
amqp "github.com/rabbitmq/amqp091-go"
|
amqp "github.com/rabbitmq/amqp091-go"
|
||||||
@@ -15,6 +16,7 @@ type Publisher interface {
|
|||||||
|
|
||||||
type RabbitPublisher struct {
|
type RabbitPublisher struct {
|
||||||
url string
|
url string
|
||||||
|
mu sync.Mutex
|
||||||
conn *amqp.Connection
|
conn *amqp.Connection
|
||||||
ch *amqp.Channel
|
ch *amqp.Channel
|
||||||
confirms chan amqp.Confirmation
|
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 {
|
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{
|
err := p.ch.PublishWithContext(ctx, "attachments", routingKey, false, false, amqp.Publishing{
|
||||||
ContentType: "application/json",
|
ContentType: "application/json",
|
||||||
DeliveryMode: amqp.Persistent,
|
DeliveryMode: amqp.Persistent,
|
||||||
@@ -85,3 +96,15 @@ func (p *RabbitPublisher) Publish(ctx context.Context, routingKey string, body [
|
|||||||
return ctx.Err()
|
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
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user