-
Notifications
You must be signed in to change notification settings - Fork 0
/
queue.go
90 lines (77 loc) · 2.08 KB
/
queue.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package hop
import (
"sync"
"github.com/pkg/errors"
"github.com/streadway/amqp"
)
// WorkQueue is an abstraction over an AMQP connection that automatically
// performs management and configuration to provide easy work queue semantics.
type WorkQueue struct {
conn *connection
config *Config
channelPool sync.Pool
}
const exchangeKind = "direct"
// DefaultQueue creates a queue with the default configuration and connection
// parameters.
func DefaultQueue(addr string) (*WorkQueue, error) {
return ConnectQueue(addr, DefaultConfig)
}
// ConnectQueue dials using the provided address string and creates a queue
// with the passed configuration.
func ConnectQueue(addr string, config *Config) (*WorkQueue, error) {
conn := newConnection(addr, config)
err := conn.connect()
if err != nil {
return nil, errors.Wrap(err, "error connecting")
}
return newQueue(conn, config)
}
func newQueue(conn *connection, config *Config) (*WorkQueue, error) {
q := &WorkQueue{
conn: conn,
config: config,
channelPool: sync.Pool{
New: conn.newChannel,
},
}
if err := q.init(); err != nil {
return nil, errors.Wrap(err, "failed to initialize queue")
}
return q, nil
}
func (q *WorkQueue) init() error {
ch, err := q.getChannel()
if err != nil {
return errors.Wrap(err, "error getting management channel")
}
defer q.putChannel(ch)
err = ch.ExchangeDeclare(q.config.ExchangeName, exchangeKind,
q.config.Persistent, false, false, false, nil)
if err != nil {
return errors.Wrap(err, "error declaring exchange")
}
return nil
}
// Close gracefully closes the connection to the message broker.
func (q *WorkQueue) Close() error {
err := q.conn.Close()
if err != nil {
return errors.Wrap(err, "error closing connection")
}
return nil
}
// --- Channels ---
func (q *WorkQueue) getChannel() (*amqp.Channel, error) {
res := q.channelPool.Get()
switch v := res.(type) {
case error:
return nil, errors.Wrap(v, "channel retrieval failed permanently")
case *amqp.Channel:
return v, nil
}
return nil, nil
}
func (q *WorkQueue) putChannel(ch *amqp.Channel) {
q.channelPool.Put(ch)
}