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