-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconsuming.go
78 lines (65 loc) · 1.39 KB
/
consuming.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
package smplmsg
import (
"fmt"
"github.com/pkg/errors"
"github.com/streadway/amqp"
)
// Consume will consume message with a given routing key on the client's exchange
func (c *client) Consume(routingKey string) (<-chan amqp.Delivery, <-chan error) {
var (
errCh = make(chan error)
queue = fmt.Sprintf("%s.%s.%s", c.exchange, c.clientID, routingKey)
)
err := c.declareQueue(queue, routingKey)
if err != nil {
errCh <- errors.Wrap(err, "failed to consume")
return nil, errCh
}
ch, err := c.amqpCh.ch.Consume(
queue,
uuid(),
false,
false,
false,
false,
nil,
)
go validateMessage(ch, errCh)
return ch, errCh
}
func validateMessage(delivCh <-chan amqp.Delivery, errCh chan error) {
for msg := range delivCh {
err := msg.Ack(false)
if err != nil {
errCh <- err
}
err = msg.Reject(true)
if err != nil {
errCh <- err
}
}
}
func (c *client) declareQueue(queue, routingKey string) error {
q, err := c.amqpCh.ch.QueueDeclare(
queue, // name of the queue
true, // durable
false, // delete when unused
false, // exclusive
false, // noWait
nil, // args
)
if err != nil {
return errors.Wrap(err, fmt.Sprintf("failed to declare queue (%s)", queue))
}
err = c.amqpCh.ch.QueueBind(
q.Name,
routingKey,
c.exchange,
false,
nil,
)
if err != nil {
return errors.Wrap(err, fmt.Sprintf("failed to bind queue (%s)", queue))
}
return nil
}