options added

This commit is contained in:
nquidox 2026-02-20 15:31:13 +03:00
parent 8b1bc57cd0
commit 3f0401de1d
5 changed files with 91 additions and 44 deletions

View file

@ -5,28 +5,27 @@ import (
amqp "github.com/rabbitmq/amqp091-go" amqp "github.com/rabbitmq/amqp091-go"
"golang.org/x/time/rate" "golang.org/x/time/rate"
"log" "log"
"time"
) )
func runConsumer(ctx context.Context, queue *Client, msgCh chan []byte) { func runConsumer(ctx context.Context, client *Client, msgCh chan []byte) {
runCtx, cancel := context.WithCancel(ctx) runCtx, cancel := context.WithCancel(ctx)
defer cancel() defer cancel()
limiter := rate.NewLimiter(rate.Every(time.Millisecond*500), 100) limiter := rate.NewLimiter(rate.Every(client.opts.consumerRateLimit), client.opts.consumerBurstSize)
deliveries, err := queue.Consume() deliveries, err := client.Consume()
if err != nil { if err != nil {
log.Printf("Could not start consuming: %s\n", err) log.Printf("Could not start consuming: %s\n", err)
return return
} }
chClosedCh := make(chan *amqp.Error, 1) chClosedCh := make(chan *amqp.Error, 1)
queue.Channel.NotifyClose(chClosedCh) client.Channel.NotifyClose(chClosedCh)
for { for {
select { select {
case <-runCtx.Done(): case <-runCtx.Done():
err = queue.Close() err = client.Close()
if err != nil { if err != nil {
log.Printf("Close failed: %s\n", err) log.Printf("Close failed: %s\n", err)
} }
@ -35,14 +34,14 @@ func runConsumer(ctx context.Context, queue *Client, msgCh chan []byte) {
case amqErr := <-chClosedCh: case amqErr := <-chClosedCh:
log.Printf("AMQP Channel closed due to: %s\n", amqErr) log.Printf("AMQP Channel closed due to: %s\n", amqErr)
deliveries, err = queue.Consume() deliveries, err = client.Consume()
if err != nil { if err != nil {
log.Println("Error trying to consume, will try again") log.Println("Error trying to consume, will try again")
continue continue
} }
chClosedCh = make(chan *amqp.Error, 1) chClosedCh = make(chan *amqp.Error, 1)
queue.Channel.NotifyClose(chClosedCh) client.Channel.NotifyClose(chClosedCh)
case delivery := <-deliveries: case delivery := <-deliveries:
msgCh <- delivery.Body msgCh <- delivery.Body

View file

@ -2,7 +2,6 @@ package rabbit
import ( import (
"context" "context"
"errors"
amqp "github.com/rabbitmq/amqp091-go" amqp "github.com/rabbitmq/amqp091-go"
"log" "log"
"os" "os"
@ -21,45 +20,48 @@ type Client struct {
notifyChanClose chan *amqp.Error notifyChanClose chan *amqp.Error
notifyConfirm chan amqp.Confirmation notifyConfirm chan amqp.Confirmation
isReady bool isReady bool
opts options
}
type options struct {
reconnectDelay time.Duration reconnectDelay time.Duration
reInitDelay time.Duration reInitDelay time.Duration
resendDelay time.Duration resendDelay time.Duration
consumerRateLimit time.Duration
consumerBurstSize int
} }
//const ( func NewClient(addr, queueName string, opts ...Option) (*Client, error) {
// reconnectDelay = 5 * time.Second if addr == "" {
// reInitDelay = 2 * time.Second return nil, errNoAddr
// resendDelay = 5 * time.Second
//)
type Deps struct {
ReconnectDelay time.Duration
ReInitDelay time.Duration
ResendDelay time.Duration
QueueName string
Addr string
} }
var ( if queueName == "" {
errNotConnected = errors.New("not connected to a server") return nil, errNoQueue
errAlreadyClosed = errors.New("already closed: not connected to the server") }
errShutdown = errors.New("client is shutting down")
)
func NewClient(deps Deps) *Client {
client := Client{ client := Client{
mutex: &sync.Mutex{}, mutex: &sync.Mutex{},
logger: log.New(os.Stdout, "", log.LstdFlags), logger: log.New(os.Stdout, "", log.LstdFlags),
queueName: deps.QueueName, queueName: queueName,
done: make(chan bool), done: make(chan bool),
reconnectDelay: deps.ReconnectDelay,
reInitDelay: deps.ReInitDelay,
resendDelay: deps.ResendDelay,
} }
go client.handleReconnect(deps.Addr) o := options{
reconnectDelay: 5,
reInitDelay: 2,
resendDelay: 5,
consumerRateLimit: time.Millisecond * 500,
consumerBurstSize: 10,
}
return &client for _, opt := range opts {
opt(&o)
}
go client.handleReconnect(addr)
return &client, nil
} }
func StartConsumer(ctx context.Context, client *Client, chanLen int) chan []byte { func StartConsumer(ctx context.Context, client *Client, chanLen int) chan []byte {

11
messages.go Normal file
View file

@ -0,0 +1,11 @@
package rabbit
import "errors"
var (
errNoAddr = errors.New("no address")
errNoQueue = errors.New("no queue")
errNotConnected = errors.New("not connected to a server")
errAlreadyClosed = errors.New("already closed: not connected to the server")
errShutdown = errors.New("client is shutting down")
)

35
options.go Normal file
View file

@ -0,0 +1,35 @@
package rabbit
import "time"
type Option func(*options)
func WithReconnectDelay(t time.Duration) Option {
return func(op *options) {
op.reconnectDelay = t
}
}
func WithReInitDelay(t time.Duration) Option {
return func(op *options) {
op.reInitDelay = t
}
}
func WithResendDelay(t time.Duration) Option {
return func(op *options) {
op.resendDelay = t
}
}
func WithConsumerRateLimit(t time.Duration) Option {
return func(op *options) {
op.consumerRateLimit = t
}
}
func WithConsumerBurstSize(t int) Option {
return func(op *options) {
op.consumerBurstSize = t
}
}

View file

@ -22,7 +22,7 @@ func (c *Client) handleReconnect(addr string) {
select { select {
case <-c.done: case <-c.done:
return return
case <-time.After(c.reconnectDelay): case <-time.After(c.opts.reconnectDelay):
} }
continue continue
} }
@ -59,7 +59,7 @@ func (c *Client) handleReInit(conn *amqp.Connection) bool {
case <-c.notifyConnClose: case <-c.notifyConnClose:
c.logger.Println("Connection closed. Reconnecting...") c.logger.Println("Connection closed. Reconnecting...")
return false return false
case <-time.After(c.reInitDelay): case <-time.After(c.opts.reInitDelay):
} }
continue continue
} }
@ -129,7 +129,7 @@ func (c *Client) Push(data []byte) error {
select { select {
case <-c.done: case <-c.done:
return errShutdown return errShutdown
case <-time.After(c.resendDelay): case <-time.After(c.opts.resendDelay):
} }
continue continue
} }