Debian Codegraph @

_examples/recovery/recovery.go

raw
1 package main
2
3 import (
4 "context"
5 "flag"
6 "fmt"
7 "log"
8 "os"
9 "os/signal"
10 "runtime"
11 "sync"
12 "syscall"
13 "time"
14
15 amqp "github.com/rabbitmq/amqp091-go"
16 )
17
18 var url = flag.String("url", "amqp://guest:guest@localhost:5672/", "AMQP URL")
19
20 func init() {
21 flag.Parse()
22 }
23
24 func main() {
25 // Enable library logging
26 amqp.Logger = log.Default()
27
28 // Register signal.NotifyContext with sigterm so that program exits gracefully on CTLR+C
29 ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
30 defer cancel()
31
32 // Create a connection with default recovery configuration
33 log.Printf("Dialing %s", *url)
34 conn, err := amqp.DialConfig(*url, amqp.Config{
35 Recovery: &amqp.Recovery{},
36 })
37 if err != nil {
38 log.Fatalf("Failed to connect to RabbitMQ: %v", err)
39 }
40 defer conn.Close()
41
42 signalBlock := sync.Cond{L: &sync.Mutex{}}
43 var isReconnecting bool
44 stateChanged := make(chan *amqp.StateChanged, 1)
45 conn.NotifyStateChange(stateChanged)
46
47 go func(ch chan *amqp.StateChanged) {
48 for statusChanged := range ch {
49 log.Printf("[connection] Status changed: %v", statusChanged)
50 switch statusChanged.To {
51 case amqp.StateOpen:
52 signalBlock.L.Lock()
53 isReconnecting = false
54 signalBlock.Broadcast()
55 signalBlock.L.Unlock()
56 case amqp.StateReconnecting:
57 log.Printf("[connection] Reconnecting to the AMQP server")
58 signalBlock.L.Lock()
59 isReconnecting = true
60 signalBlock.L.Unlock()
61 case amqp.StateClosed:
62 if statusChanged.Err != nil {
63 log.Printf("[connection] Connection closed with error: %v", statusChanged.Err)
64 } else {
65 log.Printf("[connection] Connection closed normally")
66 }
67 signalBlock.L.Lock()
68 isReconnecting = false
69 signalBlock.Broadcast()
70 signalBlock.L.Unlock()
71 cancel()
72 }
73 }
74 }(stateChanged)
75
76 ch, err := conn.Channel()
77 if err != nil {
78 log.Fatalf("Failed to open a channel: %v", err)
79 }
80 defer ch.Close()
81
82 chanStateChanged := make(chan *amqp.StateChanged, 1)
83 ch.NotifyStateChange(chanStateChanged)
84
85 go func(c chan *amqp.StateChanged) {
86 for statusChanged := range c {
87 log.Printf("[channel] Status changed: %v", statusChanged)
88 }
89 }(chanStateChanged)
90
91 queueName := "recovery_test_queue"
92 q, err := ch.QueueDeclare(
93 queueName,
94 true, // durable
95 false, // auto-delete
96 false, // exclusive
97 false, // no-wait
98 nil, // args
99 )
100 if err != nil {
101 log.Fatalf("Failed to declare a queue: %v", err)
102 }
103
104 var wg sync.WaitGroup
105
106 // Consumer goroutine will continuously consume message
107 wg.Add(1)
108 go func() {
109 defer wg.Done()
110
111 msgs, err := ch.Consume(
112 q.Name,
113 "recovery-consumer", // consumer tag
114 true, // auto-ack
115 false, // exclusive
116 false, // no-local
117 false, // no-wait
118 nil, // args
119 )
120 if err != nil {
121 log.Printf("Failed to register a consumer: %v", err)
122 return
123 }
124
125 log.Println("Consumer started. Waiting for messages...")
126 for {
127 select {
128 case <-ctx.Done():
129 log.Println("Context cancelled, stopping consumer")
130 return
131 case d, ok := <-msgs:
132 if !ok {
133 // Note: Consume channel does not close during automatic recovery.
134 // It simply blocks until recovery is complete and new messages arrive.
135 // If it does close, it means recovery failed or was disabled.
136 log.Println("Consumer channel closed")
137 return
138 }
139 log.Printf("Received: %s", d.Body)
140 }
141 }
142 }()
143
144 // Publisher goroutine will continuously publish message
145 wg.Add(1)
146 go func() {
147 defer wg.Done()
148
149 counter := 1
150 ticker := time.NewTicker(2 * time.Second)
151 defer ticker.Stop()
152
153 log.Println("Publisher started. Publishing messages...")
154 for {
155 select {
156 case <-ctx.Done():
157 log.Println("Context cancelled, stopping publisher")
158 return
159 case <-ticker.C:
160 body := fmt.Sprintf("Message %d", counter)
161 err := ch.PublishWithContext(ctx,
162 "", // exchange
163 q.Name, // routing key
164 false, // mandatory
165 false, // immediate
166 amqp.Publishing{
167 ContentType: "text/plain",
168 Body: []byte(body),
169 })
170 if err != nil {
171 log.Printf("Failed to publish message %d: %v", counter, err)
172 log.Println("Publisher is blocked, waiting for recovery...")
173 time.Sleep(10 * time.Millisecond) // Let the notifier run to update the state
174 signalBlock.L.Lock()
175 for isReconnecting { // Avoid spurious wakeups
176 signalBlock.Wait()
177 }
178 signalBlock.L.Unlock()
179 log.Println("Publisher is unblocked")
180 // Retry publishing the same message
181 continue
182 } else {
183 log.Printf("Published: %s", body)
184 }
185 counter++
186 }
187 }
188 }()
189
190 // Stats will continuously monitor the number of active goroutines every 1 minute
191 wg.Add(1)
192 go func() {
193 defer wg.Done()
194
195 ticker := time.NewTicker(1 * time.Minute)
196 defer ticker.Stop()
197
198 log.Println("Stats started. Monitoring goroutines...")
199 for {
200 select {
201 case <-ctx.Done():
202 log.Println("Context cancelled, stopping stats")
203 return
204 case <-ticker.C:
205 log.Printf("[stats] Goroutines: %d", runtime.NumGoroutine())
206 }
207 }
208 }()
209
210 log.Println("Running. Press CTRL+C to exit.")
211
212 // Wait for goroutines to finish
213 wg.Wait()
214 log.Println("Shutting down gracefully.")
215 }