-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathconnection.go
53 lines (40 loc) · 1.38 KB
/
connection.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package alice
import (
"fmt"
"time"
"github.com/rs/zerolog/log"
"github.com/streadway/amqp"
)
// connection models a RabbitMQ connection
type connection struct {
conn *amqp.Connection // The connection to the RabbitMQ broker
errorHandler func(error) // The error handler for this connection
config ConnectionConfig // Configuration for connection
}
// shutdown shuts down the connection to rabbitmq
func (c *connection) shutdown() {
c.conn.Close()
}
// Handle automatic restarting on connection closed
// t is either "consumer" or "producer"
func (c *connection) reconnect(t string, ch chan *amqp.Error) {
err := <-ch // Connection was closed for some reason
log.Err(err).Str("connType", t).Msg("connection was closed")
// Create new ticker with the desired connection delay time
ticker := time.NewTicker(c.config.reconnectDelay)
for {
<-ticker.C // New tick
var err error
log.Info().Str("connType", t).Msg("attempting to reconnect")
c.conn, err = amqp.Dial("amqp://" + c.config.user + ":" + c.config.password + "@" + c.config.host + ":" + fmt.Sprint(c.config.port))
if err != nil {
log.Error().AnErr("err", err).Str("connType", t).Msg("failed to reconnect")
}
if !c.conn.IsClosed() {
go c.reconnect(t, c.conn.NotifyClose(make(chan *amqp.Error)))
ticker.Stop()
break
}
}
log.Info().Str("connType", t).Msg("successfully reconnected")
}