Skip to content

Instantly share code, notes, and snippets.

@svcavallar
Created September 20, 2016 22:23
Show Gist options
  • Save svcavallar/be2d40953eaf27842cba2d46de9c1fb1 to your computer and use it in GitHub Desktop.
Save svcavallar/be2d40953eaf27842cba2d46de9c1fb1 to your computer and use it in GitHub Desktop.
Golang example to reconnect to RabbitMQ on a connection closed event
package main
import (
"flag"
"github.com/streadway/amqp"
"log"
"time"
)
var amqpUri = flag.String("r", "amqp://guest:guest@127.0.0.1/", "RabbitMQ URI")
var (
rabbitConn *amqp.Connection
rabbitCloseError chan *amqp.Error
)
// Try to connect to the RabbitMQ server as
// long as it takes to establish a connection
//
func connectToRabbitMQ(uri string) *amqp.Connection {
for {
conn, err := amqp.Dial(uri)
if err == nil {
return conn
}
log.Println(err)
log.Printf("Trying to reconnect to RabbitMQ at %s\n", uri)
time.Sleep(500 * time.Millisecond)
}
}
// re-establish the connection to RabbitMQ in case
// the connection has died
//
func rabbitConnector(uri string) {
var rabbitErr *amqp.Error
for {
rabbitErr = <-rabbitCloseError
if rabbitErr != nil {
log.Printf("Connecting to %s\n", *amqpUri)
rabbitConn = connectToRabbitMQ(uri)
rabbitCloseError = make(chan *amqp.Error)
rabbitConn.NotifyClose(rabbitCloseError)
// run your setup process here
}
}
}
func main() {
flag.Parse()
// create the rabbitmq error channel
rabbitCloseError = make(chan *amqp.Error)
// run the callback in a separate thread
go rabbitConnector(*amqpUri)
// establish the rabbitmq connection by sending
// an error and thus calling the error callback
rabbitCloseError <- amqp.ErrClosed
}
@neumachen
Copy link

How would you make this work with a producer?

@tomekbielaszewski
Copy link

tomekbielaszewski commented Sep 18, 2018

How would you make this work with a producer?

Here you have complete example of producing messages and consuming them after connection closed event
Code is based on this gist of course
https://gist.github.com/tomekbielaszewski/51d580ca69dcaa994995a2b16cbdc706

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment