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
|
// 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)
|
||||||
|
|
||||||
for {
|
go func() {
|
||||||
select {
|
defer close(done)
|
||||||
case msg, ok := <-msgs:
|
for {
|
||||||
if !ok {
|
select {
|
||||||
log.Println("Message channel closed, reconnecting...")
|
case msg, ok := <-msgs:
|
||||||
r.channel.Close()
|
if !ok {
|
||||||
r.conn.Close()
|
log.Println("Message channel closed, reconnecting...")
|
||||||
time.Sleep(5 * time.Second)
|
return
|
||||||
return // Break inner loop to reconnect
|
}
|
||||||
|
messageHandler(ctx, msg.Body)
|
||||||
|
case <-ctx.Done():
|
||||||
|
log.Println("Context canceled, shutting down...")
|
||||||
|
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