mt-rabbit/handler.go

74 lines
1.4 KiB
Go
Raw Permalink Normal View History

2026-02-20 14:20:04 +03:00
package rabbit
import (
"context"
amqp "github.com/rabbitmq/amqp091-go"
"log"
"os"
"sync"
"time"
)
type Client struct {
mutex *sync.Mutex
queueName string
logger *log.Logger
connection *amqp.Connection
Channel *amqp.Channel
done chan bool
notifyConnClose chan *amqp.Error
notifyChanClose chan *amqp.Error
notifyConfirm chan amqp.Confirmation
isReady bool
2026-02-20 15:31:13 +03:00
opts options
2026-02-20 14:20:04 +03:00
}
2026-02-20 15:31:13 +03:00
type options struct {
reconnectDelay time.Duration
reInitDelay time.Duration
resendDelay time.Duration
consumerRateLimit time.Duration
consumerBurstSize int
2026-02-20 14:20:04 +03:00
}
2026-02-20 16:33:15 +03:00
func NewClient(addr, queueName string, opts ...Option) *Client {
2026-02-20 15:31:13 +03:00
if addr == "" {
2026-02-20 16:33:15 +03:00
log.Fatal(errNoAddr)
2026-02-20 15:31:13 +03:00
}
if queueName == "" {
2026-02-20 16:33:15 +03:00
log.Fatal(errNoQueue)
2026-02-20 15:31:13 +03:00
}
2026-02-20 14:20:04 +03:00
client := Client{
2026-02-20 15:31:13 +03:00
mutex: &sync.Mutex{},
logger: log.New(os.Stdout, "", log.LstdFlags),
queueName: queueName,
done: make(chan bool),
}
o := options{
reconnectDelay: 5,
reInitDelay: 2,
resendDelay: 5,
consumerRateLimit: time.Millisecond * 500,
consumerBurstSize: 10,
}
for _, opt := range opts {
opt(&o)
2026-02-20 14:20:04 +03:00
}
2026-02-20 15:31:13 +03:00
go client.handleReconnect(addr)
2026-02-20 14:20:04 +03:00
2026-02-20 18:29:00 +03:00
return &client
2026-02-20 14:20:04 +03:00
}
2026-02-20 16:20:09 +03:00
func NewPublisher(client *Client) Publisher {
return &pubHandler{client: client}
2026-02-20 14:20:04 +03:00
}
2026-02-20 16:05:12 +03:00
2026-02-20 16:20:09 +03:00
func NewConsumer(ctx context.Context, client *Client, chanLen int) Consumer {
return &consumeHandler{ctx: ctx, client: client, chanLen: chanLen}
2026-02-20 16:05:12 +03:00
}