Skip to content

Instantly share code, notes, and snippets.

@amitizle
Created November 10, 2019 15:47
Show Gist options
  • Save amitizle/a1c35dcbc85d90f54e8c820b2630b92a to your computer and use it in GitHub Desktop.
Save amitizle/a1c35dcbc85d90f54e8c820b2630b92a to your computer and use it in GitHub Desktop.
Golang AMQP: Wait for rabbitmq to accept connections using
package main
import (
"fmt"
"log"
"net"
"time"
"github.com/streadway/amqp"
)
const (
retryInterval = 5 * time.Second
retryLimit = 60 * time.Second
)
func main() {
amqpConfig := &amqp.Config{
Dial: customDial,
}
log.Printf("amqpConfig: %+v", amqpConfig)
conn, err := amqp.DialConfig("amqp://127.0.0.1:5672", *amqpConfig)
if err != nil {
log.Fatal(err)
}
log.Printf("conn %+v successful", conn)
}
func customDial(network, addr string) (net.Conn, error) {
log.Print("validating connection to amqp")
var err error
var conn net.Conn
timeout := time.After(retryLimit)
ticker := time.NewTicker(retryInterval)
for {
select {
case <-timeout:
return nil, fmt.Errorf("could not connect to db after %.0f seconds (last error: %v", retryInterval.Seconds(), err)
case <-ticker.C:
conn, err = net.Dial(network, addr)
if err != nil {
log.Printf("could not connect to amqp:: %v", err)
continue
}
log.Print("connection to amqp successful")
if err := conn.SetDeadline(time.Now().Add(retryLimit)); err != nil {
return nil, err
}
return conn, nil
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment