-
Notifications
You must be signed in to change notification settings - Fork 0
/
rabbitmq.go
79 lines (66 loc) · 1.45 KB
/
rabbitmq.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
package main
import (
"log"
"github.com/streadway/amqp"
)
func ConnectToRabbitMQ(settings Settings) RabbitStream {
conn, err := amqp.Dial(settings.RabbitMQ.ConnectionString)
if err != nil {
log.Fatal(err, "Failed to open connection to amqp server.")
}
// name
// durable
// delete when unused
// exclusive
// no-wait
// arguments
ch, q := PrepareListeningQueue(conn, settings)
for _, b := range settings.RabbitMQ.Bindings {
err = ch.ExchangeDeclare(b.Exchange, amqp.ExchangeTopic, true, true, false, false, nil)
if err != nil {
log.Fatal("Failed to declare exchange. ", err)
}
if err != nil {
log.Fatal("Unable to declare exchange")
}
ch.QueueBind(q.Name, b.Topic, b.Exchange, false, nil)
}
msgs, err := ch.Consume(
q.Name, // queue
"", // consumer
false, // auto-ack
false, // exclusive
false, // no-local
false, // no-wait
nil, // args
)
return RabbitStream{
conn: conn,
channel: ch,
messages: msgs,
}
}
func PrepareListeningQueue(conn *amqp.Connection, settings Settings) (*amqp.Channel, amqp.Queue) {
ch, err := conn.Channel()
if err != nil {
log.Fatal(err, "Failed to open channel.")
}
q, err := ch.QueueDeclare(
settings.RabbitMQ.ChannelName,
true,
false,
false,
false,
nil,
)
return ch, q
}
type RabbitStream struct {
conn *amqp.Connection
channel *amqp.Channel
messages <-chan amqp.Delivery
}
func (s RabbitStream) Close() {
s.channel.Close()
s.conn.Close()
}