fix reconnection logic

This commit is contained in:
merdan 2024-10-08 17:09:45 +05:00
parent 332e3a15c5
commit 9357e8387d
1 changed files with 37 additions and 16 deletions

View File

@ -137,26 +137,47 @@ func (r *rabbitMQ) Consume(messageHandler func(ctx context.Context, body []byte)
} }
// Start message processing // Start message processing
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
defer cancel() // Create a channel to signal when message processing is done
done := make(chan bool)
go func() {
defer close(done)
for { for {
select { select {
case msg, ok := <-msgs: case msg, ok := <-msgs:
if !ok { if !ok {
log.Println("Message channel closed, reconnecting...") log.Println("Message channel closed, reconnecting...")
r.channel.Close() return
r.conn.Close()
time.Sleep(5 * time.Second)
return // Break inner loop to reconnect
} }
messageHandler(ctx, msg.Body) messageHandler(ctx, msg.Body)
case <-ctx.Done(): case <-ctx.Done():
log.Println("Context canceled, shutting down...") log.Println("Context canceled, shutting down...")
r.channel.Close()
r.conn.Close()
return return
} }
} }
}()
// Wait for either the done signal or a connection error
select {
case <-done:
// Message processing stopped, attempt to reconnect
case <-r.conn.NotifyClose(make(chan *amqp.Error)):
// Connection was closed, attempt to reconnect
}
cancel() // Cancel the context to stop message processing
r.cleanup()
log.Println("Reconnecting in 5 seconds...")
time.Sleep(5 * time.Second)
} }
} }
func (r *rabbitMQ) cleanup() {
if r.channel != nil {
r.channel.Close()
}
if r.conn != nil {
r.conn.Close()
}
}