-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathconsumer.go
102 lines (94 loc) · 2.37 KB
/
consumer.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
91
92
93
94
95
96
97
98
99
100
101
102
package sneaker
import (
"github.com/imdario/mergo"
"github.com/streadway/amqp"
)
type Consumer struct {
Connection *amqp.Connection
Channel *amqp.Channel
ExchangeName string
}
type fn func([]byte)
func NewConsumer(amqpUrl, exchangeName string) (*Consumer, error) {
amqpConn, err := amqp.Dial(amqpUrl)
if err != nil {
return nil, err
}
channel, err := amqpConn.Channel()
if err != nil {
return nil, err
}
if exchangeName == "" {
exchangeName = "go_sneaker"
}
consumer := Consumer{Connection: amqpConn,
Channel: channel, ExchangeName: exchangeName}
return &consumer, nil
}
// consume a worker queue
// exchaneName - exchange Name
// queueName - queueName
func (c *Consumer) Consume(queueName string, args map[string]interface{}, f fn) error {
defaultArgs := map[string]interface{}{
"durable": true, "autoDelete": false, "autoAck": false,
"exclusive": false, "noWait": false,
"noLocal": false, "consumer": "", "threads": 5}
if err := mergo.Merge(&defaultArgs, args, mergo.WithOverride); err != nil {
return err
}
err := c.Channel.ExchangeDeclare(
c.ExchangeName, // name
"direct", // type
true, // durable
false, // auto-deleted
false, // internal
false, // no-wait
nil, // arguments
)
if err != nil {
return err
}
queue, err := c.Channel.QueueDeclare(
queueName, // name
defaultArgs["durable"].(bool), // durable
defaultArgs["autoDelete"].(bool), // delete when unused
defaultArgs["exclusive"].(bool), // exclusive
defaultArgs["noWait"].(bool), // no-wait
nil, // arguments
)
err = c.Channel.QueueBind(
queue.Name, // queue name
queue.Name, // routing key
c.ExchangeName, // exchange
false,
nil)
if err != nil {
return err
}
msgs, err := c.Channel.Consume(
queue.Name, defaultArgs["consumer"].(string),
defaultArgs["autoAck"].(bool), defaultArgs["exclusive"].(bool),
defaultArgs["noLocal"].(bool), defaultArgs["noWait"].(bool),
nil)
if err != nil {
return err
}
go func() {
defer c.Connection.Close()
defer c.Channel.Close()
forever := make(chan bool)
threadCount := defaultArgs["threads"].(int)
for i := 0; i < threadCount; i++ {
go func() {
for msg := range msgs {
f(msg.Body)
if !defaultArgs["autoAck"].(bool) {
msg.Ack(false)
}
}
}()
}
<-forever
}()
return nil
}