How do I handle reconnections and backoffs in RabbitMQ using Go?

RabbitMQ, Go, reconnections, backoffs, message queue, Go lang, Go RabbitMQ client
Learn how to handle reconnections and implement backoff strategies while using RabbitMQ with Go. This guide provides practical examples to manage connection stability.
package main

import (
    "fmt"
    "time"

    "github.com/streadway/amqp"
)

func connectRabbitMQ() (*amqp.Connection, error) {
    // Replace with your RabbitMQ server details
    conn, err := amqp.Dial("amqp://guest:guest@localhost:5672/")
    if err != nil {
        return nil, fmt.Errorf("failed to connect to RabbitMQ: %w", err)
    }
    return conn, nil
}

func main() {
    var conn *amqp.Connection
    var err error

    // Set initial backoff duration
    backoffDuration := 1 * time.Second

    for {
        // Attempt to connect to RabbitMQ
        conn, err = connectRabbitMQ()
        if err != nil {
            fmt.Println(err)
            time.Sleep(backoffDuration)

            // Increase backoff duration exponentially
            backoffDuration *= 2
            if backoffDuration > 30*time.Second {
                backoffDuration = 30 * time.Second
            }
            continue
        }

        fmt.Println("Successfully connected to RabbitMQ!")
        backoffDuration = 1 * time.Second  // Reset backoff after successful connection
        defer conn.Close()

        // You can implement your message publishing/subscribing logic here
        break // Exit loop if connection successful
    }
}

RabbitMQ Go reconnections backoffs message queue Go lang Go RabbitMQ client