Debian Codegraph @

_examples/producer/producer.go

raw symbols SCIP
1 // This example declares a durable exchange, and publishes one messages to that
2 // exchange. This example allows up to 8 outstanding publisher confirmations
3 // before blocking publishing.
4 package main
5
6 import (
7 "flag"
8 "log"
9 "os"
10 "os/signal"
11 "syscall"
12 "time"
13
14 amqp "github.com/rabbitmq/amqp091-go"
15 )
16
17 var (
18 uri = flag.String("uri", "amqp://guest:guest@localhost:5672/", "AMQP URI")
19 exchange = flag.String("exchange", "test-exchange", "Durable AMQP exchange name")
20 exchangeType = flag.String("exchange-type", "direct", "Exchange type - direct|fanout|topic|x-custom")
21 queue = flag.String("queue", "test-queue", "Ephemeral AMQP queue name")
22 routingKey = flag.String("key", "test-key", "AMQP routing key")
23 body = flag.String("body", "foobar", "Body of message")
24 continuous = flag.Bool("continuous", false, "Keep publishing messages at a 1msg/sec rate")
25 WarnLog = log.New(os.Stderr, "[WARNING] ", log.LstdFlags|log.Lmsgprefix)
26 ErrLog = log.New(os.Stderr, "[ERROR] ", log.LstdFlags|log.Lmsgprefix)
27 Log = log.New(os.Stdout, "[INFO] ", log.LstdFlags|log.Lmsgprefix)
28 )
29
30 func init() {
31 flag.Parse()
32 }
33
34 func main() {
35 exitCh := make(chan struct{})
36 confirmsCh := make(chan *amqp.DeferredConfirmation)
37 confirmsDoneCh := make(chan struct{})
38 // Note: this is a buffered channel so that indicating OK to
39 // publish does not block the confirm handler
40 publishOkCh := make(chan struct{}, 1)
41
42 setupCloseHandler(exitCh)
43
44 startConfirmHandler(publishOkCh, confirmsCh, confirmsDoneCh, exitCh)
45
46 publish(publishOkCh, confirmsCh, confirmsDoneCh, exitCh)
47 }
48
49 func setupCloseHandler(exitCh chan struct{}) {
50 c := make(chan os.Signal, 2)
51 signal.Notify(c, os.Interrupt, syscall.SIGTERM)
52 go func() {
53 <-c
54 Log.Printf("close handler: Ctrl+C pressed in Terminal")
55 close(exitCh)
56 }()
57 }
58
59 func publish(publishOkCh <-chan struct{}, confirmsCh chan<- *amqp.DeferredConfirmation, confirmsDoneCh <-chan struct{}, exitCh chan struct{}) {
60 config := amqp.Config{
61 Vhost: "/",
62 Properties: amqp.NewConnectionProperties(),
63 }
64 config.Properties.SetClientConnectionName("producer-with-confirms")
65
66 Log.Printf("producer: dialing %s", *uri)
67 conn, err := amqp.DialConfig(*uri, config)
68 if err != nil {
69 ErrLog.Fatalf("producer: error in dial: %s", err)
70 }
71 defer conn.Close()
72
73 Log.Println("producer: got Connection, getting Channel")
74 channel, err := conn.Channel()
75 if err != nil {
76 ErrLog.Fatalf("error getting a channel: %s", err)
77 }
78 defer channel.Close()
79
80 Log.Printf("producer: declaring exchange")
81 if err := channel.ExchangeDeclare(
82 *exchange, // name
83 *exchangeType, // type
84 true, // durable
85 false, // auto-delete
86 false, // internal
87 false, // noWait
88 nil, // arguments
89 ); err != nil {
90 ErrLog.Fatalf("producer: Exchange Declare: %s", err)
91 }
92
93 Log.Printf("producer: declaring queue '%s'", *queue)
94 queue, err := channel.QueueDeclare(
95 *queue, // name of the queue
96 true, // durable
97 false, // delete when unused
98 false, // exclusive
99 false, // noWait
100 nil, // arguments
101 )
102 if err == nil {
103 Log.Printf("producer: declared queue (%q %d messages, %d consumers), binding to Exchange (key %q)",
104 queue.Name, queue.Messages, queue.Consumers, *routingKey)
105 } else {
106 ErrLog.Fatalf("producer: Queue Declare: %s", err)
107 }
108
109 Log.Printf("producer: declaring binding")
110 if err := channel.QueueBind(queue.Name, *routingKey, *exchange, false, nil); err != nil {
111 ErrLog.Fatalf("producer: Queue Bind: %s", err)
112 }
113
114 // Reliable publisher confirms require confirm.select support from the
115 // connection.
116 Log.Printf("producer: enabling publisher confirms.")
117 if err := channel.Confirm(false); err != nil {
118 ErrLog.Fatalf("producer: channel could not be put into confirm mode: %s", err)
119 }
120
121 for {
122 canPublish := false
123 Log.Println("producer: waiting on the OK to publish...")
124 for {
125 select {
126 case <-confirmsDoneCh:
127 Log.Println("producer: stopping, all confirms seen")
128 return
129 case <-publishOkCh:
130 Log.Println("producer: got the OK to publish")
131 canPublish = true
132 break
133 case <-time.After(time.Second):
134 WarnLog.Println("producer: still waiting on the OK to publish...")
135 continue
136 }
137 if canPublish {
138 break
139 }
140 }
141
142 Log.Printf("producer: publishing %dB body (%q)", len(*body), *body)
143 dConfirmation, err := channel.PublishWithDeferredConfirm(
144 *exchange,
145 *routingKey,
146 true,
147 false,
148 amqp.Publishing{
149 Headers: amqp.Table{},
150 ContentType: "text/plain",
151 ContentEncoding: "",
152 DeliveryMode: amqp.Persistent,
153 Priority: 0,
154 AppId: "sequential-producer",
155 Body: []byte(*body),
156 },
157 )
158 if err != nil {
159 ErrLog.Fatalf("producer: error in publish: %s", err)
160 }
161
162 select {
163 case <-confirmsDoneCh:
164 Log.Println("producer: stopping, all confirms seen")
165 return
166 case confirmsCh <- dConfirmation:
167 Log.Println("producer: delivered deferred confirm to handler")
168 break
169 }
170
171 select {
172 case <-confirmsDoneCh:
173 Log.Println("producer: stopping, all confirms seen")
174 return
175 case <-time.After(time.Millisecond * 250):
176 if *continuous {
177 continue
178 } else {
179 Log.Println("producer: initiating stop")
180 close(exitCh)
181 select {
182 case <-confirmsDoneCh:
183 Log.Println("producer: stopping, all confirms seen")
184 return
185 case <-time.After(time.Second * 10):
186 WarnLog.Println("producer: may be stopping with outstanding confirmations")
187 return
188 }
189 }
190 }
191 }
192 }
193
194 func startConfirmHandler(publishOkCh chan<- struct{}, confirmsCh <-chan *amqp.DeferredConfirmation, confirmsDoneCh chan struct{}, exitCh <-chan struct{}) {
195 go func() {
196 confirms := make(map[uint64]*amqp.DeferredConfirmation)
197
198 for {
199 select {
200 case <-exitCh:
201 exitConfirmHandler(confirms, confirmsDoneCh)
202 return
203 default:
204 break
205 }
206
207 outstandingConfirmationCount := len(confirms)
208
209 // Note: 8 is arbitrary, you may wish to allow more outstanding confirms before blocking publish
210 if outstandingConfirmationCount <= 8 {
211 select {
212 case publishOkCh <- struct{}{}:
213 Log.Println("confirm handler: sent OK to publish")
214 case <-time.After(time.Second * 5):
215 WarnLog.Println("confirm handler: timeout indicating OK to publish (this should never happen!)")
216 }
217 } else {
218 WarnLog.Printf("confirm handler: waiting on %d outstanding confirmations, blocking publish", outstandingConfirmationCount)
219 }
220
221 select {
222 case confirmation := <-confirmsCh:
223 dtag := confirmation.DeliveryTag
224 confirms[dtag] = confirmation
225 case <-exitCh:
226 exitConfirmHandler(confirms, confirmsDoneCh)
227 return
228 }
229
230 checkConfirmations(confirms)
231 }
232 }()
233 }
234
235 func exitConfirmHandler(confirms map[uint64]*amqp.DeferredConfirmation, confirmsDoneCh chan struct{}) {
236 Log.Println("confirm handler: exit requested")
237 waitConfirmations(confirms)
238 close(confirmsDoneCh)
239 Log.Println("confirm handler: exiting")
240 }
241
242 func checkConfirmations(confirms map[uint64]*amqp.DeferredConfirmation) {
243 Log.Printf("confirm handler: checking %d outstanding confirmations", len(confirms))
244 for k, v := range confirms {
245 if v.Acked() {
246 Log.Printf("confirm handler: confirmed delivery with tag: %d", k)
247 delete(confirms, k)
248 }
249 }
250 }
251
252 func waitConfirmations(confirms map[uint64]*amqp.DeferredConfirmation) {
253 Log.Printf("confirm handler: waiting on %d outstanding confirmations", len(confirms))
254
255 checkConfirmations(confirms)
256
257 for k, v := range confirms {
258 select {
259 case <-v.Done():
260 Log.Printf("confirm handler: confirmed delivery with tag: %d", k)
261 delete(confirms, k)
262 case <-time.After(time.Second):
263 WarnLog.Printf("confirm handler: did not receive confirmation for tag %d", k)
264 }
265 }
266
267 outstandingConfirmationCount := len(confirms)
268 if outstandingConfirmationCount > 0 {
269 ErrLog.Printf("confirm handler: exiting with %d outstanding confirmations", outstandingConfirmationCount)
270 } else {
271 Log.Println("confirm handler: done waiting on outstanding confirmations")
272 }
273 }