This repository has been archived by the owner on Oct 12, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 52
/
queue_examples_test.go
343 lines (286 loc) · 9.54 KB
/
queue_examples_test.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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
package servicebus_test
import (
"bytes"
"context"
"fmt"
"math/rand"
"os"
"time"
"github.com/Azure/azure-amqp-common-go/v3/uuid"
"github.com/Azure/azure-service-bus-go"
"github.com/joho/godotenv"
)
func init() {
if err := godotenv.Load(); err != nil {
fmt.Println("FATAL: ", err)
}
}
func ExampleQueue_getOrBuildQueue() {
const queueName = "myqueue"
connStr := os.Getenv("SERVICEBUS_CONNECTION_STRING")
if connStr == "" {
fmt.Println("FATAL: expected environment variable SERVICEBUS_CONNECTION_STRING not set")
return
}
ns, err := servicebus.NewNamespace(servicebus.NamespaceWithConnectionString(connStr))
if err != nil {
fmt.Println(err)
return
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
qm := ns.NewQueueManager()
qe, err := qm.Get(ctx, queueName)
if err != nil && !servicebus.IsErrNotFound(err) {
fmt.Println(err)
return
}
if qe == nil {
_, err := qm.Put(ctx, queueName)
if err != nil {
fmt.Println(err)
return
}
}
q, err := ns.NewQueue(queueName)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(q.Name)
// Output: myqueue
}
func ExampleQueue_Send() {
// Instantiate the clients needed to communicate with a Service Bus Queue.
ns, err := servicebus.NewNamespace(servicebus.NamespaceWithConnectionString("<your connection string here>"))
if err != nil {
return
}
client, err := ns.NewQueue("myqueue")
if err != nil {
return
}
// Create a context to limit how long we will try to send, then push the message over the wire.
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := client.Send(ctx, servicebus.NewMessageFromString("Hello World!!!")); err != nil {
fmt.Println("FATAL: ", err)
}
}
func ExampleQueue_Receive() {
// Define a function that should be executed when a message is received.
var printMessage servicebus.HandlerFunc = func(ctx context.Context, msg *servicebus.Message) error {
fmt.Println(string(msg.Data))
return msg.Complete(ctx)
}
// Instantiate the clients needed to communicate with a Service Bus Queue.
ns, err := servicebus.NewNamespace(servicebus.NamespaceWithConnectionString("<your connection string here>"))
if err != nil {
return
}
client, err := ns.NewQueue("myqueue")
if err != nil {
return
}
// Define a context to limit how long we will block to receive messages, then start serving our function.
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
defer cancel()
if err := client.Receive(ctx, printMessage); err != nil {
fmt.Println("FATAL: ", err)
}
}
func ExampleQueue_Receive_second() {
// Set concurrent number
const concurrentNum = 5
// Define msg chan
msgChan := make(chan *servicebus.Message, concurrentNum)
// Define a function that should be executed when a message is received.
var concurrentHandler servicebus.HandlerFunc = func(ctx context.Context, msg *servicebus.Message) error {
msgChan <- msg
return nil
}
// Define msg workers
for i := 0; i < concurrentNum; i++ {
go func() {
for msg := range msgChan {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Millisecond)
defer cancel()
fmt.Println(string(msg.Data))
msg.Complete(ctx)
}
}()
}
// Instantiate the clients needed to communicate with a Service Bus Queue.
ns, err := servicebus.NewNamespace(servicebus.NamespaceWithConnectionString("<your connection string here>"))
if err != nil {
close(msgChan)
return
}
// Init queue client with prefetch count
client, err := ns.NewQueue("myqueue", servicebus.QueueWithPrefetchCount(concurrentNum))
if err != nil {
close(msgChan)
return
}
// Define a context to limit how long we will block to receive messages, then start serving our function.
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
defer cancel()
if err := client.Receive(ctx, concurrentHandler); err != nil {
fmt.Println("FATAL: ", err)
}
// Close the message chan
close(msgChan)
}
func ExampleQueue_scheduleAndCancelMessages() {
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Minute+40*time.Second)
defer cancel()
connStr := os.Getenv("SERVICEBUS_CONNECTION_STRING")
if connStr == "" {
fmt.Println("FATAL: expected environment variable SERVICEBUS_CONNECTION_STRING not set")
return
}
// Create a client to communicate with a Service Bus Namespace.
ns, err := servicebus.NewNamespace(servicebus.NamespaceWithConnectionString(connStr))
if err != nil {
fmt.Println("FATAL: ", err)
return
}
client, err := ns.NewQueue("schedulewithqueue")
if err != nil {
fmt.Println("FATAL: ", err)
return
}
// The delay that we should schedule a message for.
const waitTime = 1 * time.Minute
expectedTime := time.Now().Add(waitTime)
msg := servicebus.NewMessageFromString("to the future!!")
scheduled, err := client.ScheduleAt(ctx, expectedTime, msg)
if err != nil {
fmt.Println("FATAL: ", err)
return
}
err = client.CancelScheduled(ctx, scheduled...)
if err != nil {
fmt.Println("FATAL: ", err)
return
}
fmt.Println("All Messages Scheduled and Cancelled")
// Output: All Messages Scheduled and Cancelled
}
func ExampleQueue_sessionsRoundTrip() {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Setup the required clients for communicating with Service Bus. //
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
connStr := os.Getenv("SERVICEBUS_CONNECTION_STRING")
if connStr == "" {
fmt.Println("FATAL: expected environment variable SERVICEBUS_CONNECTION_STRING not set")
return
}
ns, err := servicebus.NewNamespace(servicebus.NamespaceWithConnectionString(connStr))
if err != nil {
fmt.Println("FATAL: ", err)
return
}
client, err := ns.NewQueue("receivesession")
if err != nil {
fmt.Println("FATAL: ", err)
return
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Publish five session's worth of data. //
// //
// The sessions are deliberately interleaved to demonstrate consumption semantics. //
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
const numSessions = 5
adjectives := []string{"Doltish", "Foolish", "Juvenile"}
nouns := []string{"Automaton", "Luddite", "Monkey", "Neanderthal"}
// seed chosen arbitrarily, see https://en.wikipedia.org/wiki/Taxicab_number
generator := rand.New(rand.NewSource(1729))
sessionIDs := make([]string, numSessions)
// Establish a set of sessions
for i := 0; i < numSessions; i++ {
if rawSessionID, err := uuid.NewV4(); err == nil {
sessionIDs[i] = rawSessionID.String()
} else {
fmt.Println("FATAL: ", err)
return
}
}
// Publish an adjective for each session
for i := 0; i < numSessions; i++ {
adj := adjectives[generator.Intn(len(adjectives))]
msg := servicebus.NewMessageFromString(adj)
msg.SessionID = &sessionIDs[i]
if err := client.Send(ctx, msg); err != nil {
fmt.Println("FATAL: ", err)
return
}
}
// Publish a noun for each session
for i := 0; i < numSessions; i++ {
noun := nouns[generator.Intn(len(nouns))]
msg := servicebus.NewMessageFromString(noun)
msg.SessionID = &sessionIDs[i]
if err := client.Send(ctx, msg); err != nil {
fmt.Println("FATAL: ", err)
return
}
}
// Publish a numeric suffix for each session
for i := 0; i < numSessions; i++ {
suffix := fmt.Sprintf("%02d", generator.Intn(100))
msg := servicebus.NewMessageFromString(suffix)
msg.SessionID = &sessionIDs[i]
if err := client.Send(ctx, msg); err != nil {
fmt.Println("FATAL: ", err)
return
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Receive and process the previously published sessions. //
// //
// The order the sessions are received in is not guaranteed, so the expected output must be "Unordered output". //
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
for i := 0; i < numSessions; i++ {
handler := &SessionPrinter{}
qs := client.NewSession(nil)
if err := qs.ReceiveOne(ctx, handler); err != nil {
fmt.Println("FATAL: ", err)
return
}
}
// Unordered output:
// FoolishMonkey63
// FoolishLuddite05
// JuvenileMonkey80
// JuvenileLuddite84
// FoolishLuddite68
}
type SessionPrinter struct {
builder *bytes.Buffer
messageSession *servicebus.MessageSession
messagesReceived uint
}
func (sp *SessionPrinter) Start(ms *servicebus.MessageSession) error {
if sp.builder == nil {
sp.builder = &bytes.Buffer{}
} else {
sp.builder.Reset()
}
sp.messagesReceived = 0
sp.messageSession = ms
return nil
}
func (sp *SessionPrinter) Handle(ctx context.Context, msg *servicebus.Message) error {
sp.builder.Write(msg.Data)
sp.messagesReceived++
if sp.messagesReceived >= 3 {
defer sp.messageSession.Close()
}
return msg.Complete(ctx)
}
func (sp *SessionPrinter) End() {
fmt.Println(sp.builder.String())
}