-
Notifications
You must be signed in to change notification settings - Fork 0
/
consumer.go
83 lines (78 loc) · 2.56 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
package rabbitmq
import (
"context"
amqp "github.com/rabbitmq/amqp091-go"
)
type Consumer struct {
Channel *amqp.Channel
ExchangeName string
QueueName string
AutoAck bool
AckOnConsume bool
LogError func(ctx context.Context, msg string)
}
func NewConsumer(channel *amqp.Channel, exchangeName string, queueName string, autoAck, ackOnConsume bool, logError func(ctx context.Context, msg string)) (*Consumer, error) {
return &Consumer{Channel: channel, ExchangeName: exchangeName, QueueName: queueName, AutoAck: autoAck, AckOnConsume: ackOnConsume, LogError: logError}, nil
}
func NewConsumerByConfig(config ConsumerConfig, autoAck, ackOnConsume bool, logError func(ctx context.Context, msg string)) (*Consumer, error) {
channel, er1 := NewChannel(config.Url)
if er1 != nil {
return nil, er1
}
err := channel.ExchangeDeclare(config.ExchangeName, config.ExchangeKind, true, config.AutoDelete, false, false, nil)
if err != nil {
return nil, err
}
queue, err := channel.QueueDeclare(config.QueueName, false, false, true, false, nil)
if err != nil {
return nil, err
}
return NewConsumer(channel, config.ExchangeName, queue.Name, autoAck, ackOnConsume, logError)
}
func (c *Consumer) Consume(ctx context.Context, handle func(context.Context, []byte, map[string]string)) {
delivery, err := c.Channel.Consume(c.QueueName, "", c.AutoAck, false, false, false, nil)
if err != nil {
c.LogError(ctx, "Error when consume: "+err.Error())
} else {
for msg := range delivery {
attributes := TableToMap(msg.Headers)
if c.AckOnConsume && !c.AutoAck {
msg.Ack(false)
}
handle(ctx, msg.Body, attributes)
}
}
}
func (c *Consumer) ConsumeBody(ctx context.Context, handle func(context.Context, []byte)) {
delivery, err := c.Channel.Consume(c.QueueName, "", c.AutoAck, false, false, false, nil)
if err != nil {
c.LogError(ctx, "Error when consume: "+err.Error())
} else {
for msg := range delivery {
if c.AckOnConsume && !c.AutoAck {
msg.Ack(false)
}
handle(ctx, msg.Body)
}
}
}
func (c *Consumer) ConsumeDelivery(ctx context.Context, handle func(context.Context, amqp.Delivery)) {
delivery, err := c.Channel.Consume(c.QueueName, "", c.AutoAck, false, false, false, nil)
if err != nil {
c.LogError(ctx, "Error when consume: "+err.Error())
} else {
for msg := range delivery {
if c.AckOnConsume && !c.AutoAck {
msg.Ack(false)
}
handle(ctx, msg)
}
}
}
func TableToMap(header amqp.Table) map[string]string {
attributes := make(map[string]string, 0)
for k, v := range header {
attributes[k] = v.(string)
}
return attributes
}