Skip to content

Instantly share code, notes, and snippets.

@iamgoangle
Last active July 15, 2019 16:20
Show Gist options
  • Select an option

  • Save iamgoangle/a5cbe982fc4e87a8c71e1d28d9635ea5 to your computer and use it in GitHub Desktop.

Select an option

Save iamgoangle/a5cbe982fc4e87a8c71e1d28d9635ea5 to your computer and use it in GitHub Desktop.
package rabbitmq
import (
"log"
"math/rand"
"time"
"github.com/streadway/amqp"
)
type ConfigConnection struct {
Url string
Type string
}
var retryTime int
// NewConnection factory connection to RabbitMQ
func NewConnection(c ConfigConnection) (conn *amqp.Connection, err error) {
return newClient(c.Url)
}
func newClient(host string) (*amqp.Connection, error) {
conn, err := amqp.Dial(host)
failOnError(err, "Failed to connect to RabbitMQ")
log.Println("Connected...")
go func() {
retryTime++
// Waits here for the channel to be closed
log.Println("closing: ", <-conn.NotifyClose(make(chan *amqp.Error)))
// retry count handler...
// if retryTime more than x times
backoff := time.Duration(15+rand.Intn(60)+2*retryTime) * time.Second
log.Printf("Re-connecting... %v in %v", retryTime, backoff)
time.Sleep(backoff)
newClient(host)
}()
return conn, err
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment