-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
81 lines (71 loc) · 2.06 KB
/
main.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
package main
import (
"log"
"time"
"github.com/cenkalti/backoff/v4"
"github.com/heureka/gorabbit/channel"
"github.com/heureka/gorabbit/connection"
amqp "github.com/rabbitmq/amqp091-go"
)
func main() {
conn, err := connection.Dial("amqp://localhost:5672")
if err != nil {
log.Panic(err)
}
bo := backoff.NewExponentialBackOff()
bo.MaxElapsedTime = 10 * time.Second
// create new channel with re-creation capabilities.
ch, err := conn.Channel(
// set up different backoff strategy.
channel.WithBackoff(bo),
// set QOS to pre-fetch 100 messages, it will be applied every time channel is created.
channel.WithQOS(100, 0, false),
// configure channel as you wish, will be applied on each successful creation of a channel.
channel.WithOpenCallback(func(ch *amqp.Channel) error {
cancelNotif := ch.NotifyCancel(make(chan string))
go func() {
for tag := range cancelNotif {
log.Println("got cancel notification", tag)
}
}()
return nil
}),
)
if err != nil {
log.Panic(err)
}
// get notification when channel will be re-opened.
reopenNotif := ch.NotifyReopen(make(chan error)) // reopenNotif will be closed on graceful shutdown
go func() {
for err := range reopenNotif {
if err != nil {
log.Println("can't re-open channel", err)
return
}
log.Println("successfully re-opened channel", err)
}
}()
// get notification when consuming has started,
// notification will be sent on every channel re-opening and resuming of consuming.
consumeNotif := ch.NotifyConsume(make(chan error)) // consumeNotif will be closed on graceful shutdown
go func() {
for err := range consumeNotif {
if err != nil {
log.Println("can't start consuming", err)
return
}
log.Println("successfully started consuming", err)
}
}()
deliveries := ch.Consume("example-queue", "", false, false, false, false, nil)
go func() {
for d := range deliveries {
// do something with deliveries
log.Println(d.Body)
}
}()
time.Sleep(10 * time.Second) // consume for 10 seconds
if err := ch.Close(); err != nil {
log.Panic(err)
}
}