fix reconnection logic
This commit is contained in:
parent
332e3a15c5
commit
9357e8387d
|
|
@ -137,26 +137,47 @@ func (r *rabbitMQ) Consume(messageHandler func(ctx context.Context, body []byte)
|
|||
}
|
||||
// Start message processing
|
||||
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 {
|
||||
select {
|
||||
case msg, ok := <-msgs:
|
||||
if !ok {
|
||||
log.Println("Message channel closed, reconnecting...")
|
||||
r.channel.Close()
|
||||
r.conn.Close()
|
||||
time.Sleep(5 * time.Second)
|
||||
return // Break inner loop to reconnect
|
||||
return
|
||||
}
|
||||
messageHandler(ctx, msg.Body)
|
||||
case <-ctx.Done():
|
||||
log.Println("Context canceled, shutting down...")
|
||||
r.channel.Close()
|
||||
r.conn.Close()
|
||||
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()
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue