-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconnection.go
74 lines (66 loc) · 1.37 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package hop
import (
"sync"
"github.com/cenkalti/backoff"
"github.com/pkg/errors"
"github.com/streadway/amqp"
)
type connection struct {
addr string
config *Config
conn *amqp.Connection
mu sync.Mutex
}
func newConnection(addr string, config *Config) *connection {
return &connection{
addr: addr,
config: config,
}
}
func (c *connection) connect() error {
c.mu.Lock()
defer c.mu.Unlock()
conn, err := c.dialWithBackOff()
if err != nil {
return errors.Wrap(err, "queue connection failed permanently")
}
c.conn = conn
return nil
}
func (c *connection) dialWithBackOff() (*amqp.Connection, error) {
var conn *amqp.Connection
connect := func() error {
var err error
if c.config.AMQPConfig != nil {
conn, err = amqp.DialConfig(c.addr, *c.config.AMQPConfig)
return err
}
conn, err = amqp.Dial(c.addr)
return err
}
b := backoff.NewExponentialBackOff()
b.MaxElapsedTime = c.config.MaxConnectionRetry
err := backoff.Retry(connect, b)
if err != nil {
return nil, errors.Wrap(err, "error dialing")
}
return conn, nil
}
func (c *connection) newChannel() interface{} {
var (
ch *amqp.Channel
err error
)
for err == nil {
ch, err = c.conn.Channel()
if err != nil {
err = c.connect()
continue
}
return ch
}
return errors.Wrap(err, "failed to initialize channel")
}
func (c *connection) Close() error {
return c.conn.Close()
}