/
ServiceBusSenderClient.java
476 lines (450 loc) · 22.8 KB
/
ServiceBusSenderClient.java
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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.messaging.servicebus;
import com.azure.core.annotation.ServiceClient;
import com.azure.core.util.IterableStream;
import com.azure.messaging.servicebus.models.CreateMessageBatchOptions;
import java.time.Duration;
import java.time.OffsetDateTime;
import java.util.Objects;
/**
* <p>A <b>synchronous</b> sender responsible for sending {@link ServiceBusMessage} to a queue or topic on
* Azure Service Bus.</p>
*
* <p>The examples shown in this document use a credential object named DefaultAzureCredential for authentication,
* which is appropriate for most scenarios, including local development and production environments. Additionally, we
* recommend using
* <a href="https://learn.microsoft.com/azure/active-directory/managed-identities-azure-resources/">managed identity</a>
* for authentication in production environments. You can find more information on different ways of authenticating and
* their corresponding credential types in the
* <a href="https://learn.microsoft.com/java/api/overview/azure/identity-readme">Azure Identity documentation"</a>.
* </p>
*
* <p><strong>Sample: Create an instance of sender</strong></p>
* <!-- src_embed com.azure.messaging.servicebus.servicebussenderclient.instantiation -->
* <pre>
* TokenCredential credential = new DefaultAzureCredentialBuilder().build();
*
* // 'fullyQualifiedNamespace' will look similar to "{your-namespace}.servicebus.windows.net"
* ServiceBusSenderClient sender = new ServiceBusClientBuilder()
* .credential(fullyQualifiedNamespace, credential)
* .sender()
* .queueName(queueName)
* .buildClient();
*
* sender.sendMessage(new ServiceBusMessage("Foo bar"));
* </pre>
* <!-- end com.azure.messaging.servicebus.servicebussenderclient.instantiation -->
*
* <p><strong>Sample: Send messages to a Service Bus resource</strong></p>
* <!-- src_embed com.azure.messaging.servicebus.servicebussenderclient.createMessageBatch -->
* <pre>
* TokenCredential credential = new DefaultAzureCredentialBuilder().build();
*
* // 'fullyQualifiedNamespace' will look similar to "{your-namespace}.servicebus.windows.net"
* ServiceBusSenderClient sender = new ServiceBusClientBuilder()
* .credential(fullyQualifiedNamespace, credential)
* .sender()
* .queueName(queueName)
* .buildClient();
*
* List<ServiceBusMessage> messages = Arrays.asList(
* new ServiceBusMessage("test-1"),
* new ServiceBusMessage("test-2"));
*
* // Creating a batch without options set.
* ServiceBusMessageBatch batch = sender.createMessageBatch();
* for (ServiceBusMessage message : messages) {
* if (batch.tryAddMessage(message)) {
* continue;
* }
*
* // The batch is full. Send the current batch and create a new one.
* sender.sendMessages(batch);
*
* batch = sender.createMessageBatch();
*
* // Add the message we couldn't before.
* if (!batch.tryAddMessage(message)) {
* throw new IllegalArgumentException("Message is too large for an empty batch.");
* }
* }
*
* // Send the final batch if there are any messages in it.
* if (batch.getCount() > 0) {
* sender.sendMessages(batch);
* }
*
* // Continue using the sender and finally, dispose of the sender.
* // Clients should be long-lived objects as they require resources
* // and time to establish a connection to the service.
* sender.close();
* </pre>
* <!-- end com.azure.messaging.servicebus.servicebussenderclient.createMessageBatch -->
*
* <p><strong>Sample: Send messages using a size-limited {@link ServiceBusMessageBatch}</strong></p>
* <!-- src_embed com.azure.messaging.servicebus.servicebussenderclient.createMessageBatch#CreateMessageBatchOptions -->
* <pre>
* List<ServiceBusMessage> telemetryMessages = Arrays.asList(firstMessage, secondMessage, thirdMessage);
*
* // Setting `setMaximumSizeInBytes` when creating a batch, limits the size of that batch.
* // In this case, all the batches created with these options are limited to 256 bytes.
* CreateMessageBatchOptions options = new CreateMessageBatchOptions()
* .setMaximumSizeInBytes(256);
*
* ServiceBusMessageBatch currentBatch = sender.createMessageBatch(options);
*
* // For each telemetry message, we try to add it to the current batch.
* // When the batch is full, send it then create another batch to add more mesages to.
* for (ServiceBusMessage message : telemetryMessages) {
* if (!currentBatch.tryAddMessage(message)) {
* sender.sendMessages(currentBatch);
* currentBatch = sender.createMessageBatch(options);
*
* // Add the message we couldn't before.
* if (!currentBatch.tryAddMessage(message)) {
* throw new IllegalArgumentException("Message is too large for an empty batch.");
* }
* }
* }
*
* // Send the final batch if there are any messages in it.
* if (currentBatch.getCount() > 0) {
* sender.sendMessages(currentBatch);
* }
*
* // Continue using the sender and finally, dispose of the sender.
* // Clients should be long-lived objects as they require resources
* // and time to establish a connection to the service.
* sender.close();
* </pre>
* <!-- end com.azure.messaging.servicebus.servicebussenderclient.createMessageBatch#CreateMessageBatchOptions -->
*
* <p><strong>Sample: Sending a message to a session-enabled queue</strong></p>
*
* <p>The snippet below demonstrates sending a message to a
* <a href="https://learn.microsoft.com/azure/service-bus-messaging/message-sessions">Service Bus sessions</a>
* enabled queue. Setting {@link ServiceBusMessage#setMessageId(String)} property to "greetings" will send the message
* to a Service Bus session with an id of "greetings".</p>
*
* <!-- src_embed com.azure.messaging.servicebus.servicebussenderclient.sendMessage-session -->
* <pre>
* // 'fullyQualifiedNamespace' will look similar to "{your-namespace}.servicebus.windows.net"
* ServiceBusSenderClient sender = new ServiceBusClientBuilder()
* .credential(fullyQualifiedNamespace, new DefaultAzureCredentialBuilder().build())
* .sender()
* .queueName(sessionEnabledQueueName)
* .buildClient();
*
* // Setting sessionId publishes that message to a specific session, in this case, "greeting".
* ServiceBusMessage message = new ServiceBusMessage("Hello world")
* .setSessionId("greetings");
*
* sender.sendMessage(message);
*
* // Dispose of the sender.
* sender.close();
* </pre>
* <!-- end com.azure.messaging.servicebus.servicebussenderclient.sendMessage-session -->
*
* @see ServiceBusClientBuilder#sender()
* @see ServiceBusSenderAsyncClient To communicate with a Service Bus resource using an asynchronous client.
*/
@ServiceClient(builder = ServiceBusClientBuilder.class)
public final class ServiceBusSenderClient implements AutoCloseable {
private final ServiceBusSenderAsyncClient asyncClient;
private final Duration tryTimeout;
/**
* Creates a new instance of {@link ServiceBusSenderClient} that sends messages to an Azure Service Bus.
*
* @throws NullPointerException if {@code asyncClient} or {@code tryTimeout} is null.
*/
ServiceBusSenderClient(ServiceBusSenderAsyncClient asyncClient, Duration tryTimeout) {
this.asyncClient = Objects.requireNonNull(asyncClient, "'asyncClient' cannot be null.");
this.tryTimeout = Objects.requireNonNull(tryTimeout, "'tryTimeout' cannot be null.");
}
/**
* Cancels the enqueuing of a scheduled message, if they are not already enqueued.
*
* @param sequenceNumber The sequence number of the message to cancel.
*
* @throws IllegalArgumentException if {@code sequenceNumber} is negative.
* @throws ServiceBusException If the message could not be cancelled.
* @throws IllegalStateException if sender is already disposed.
*/
public void cancelScheduledMessage(long sequenceNumber) {
asyncClient.cancelScheduledMessage(sequenceNumber).block(tryTimeout);
}
/**
* Cancels the enqueuing of scheduled messages, if they are not already enqueued.
*
* @param sequenceNumbers The sequence numbers of messages to cancel.
*
* @throws NullPointerException if {@code sequenceNumbers} is null.
* @throws ServiceBusException If the messages could not be cancelled.
* @throws IllegalStateException if sender is already disposed.
*/
public void cancelScheduledMessages(Iterable<Long> sequenceNumbers) {
asyncClient.cancelScheduledMessages(sequenceNumbers).block(tryTimeout);
}
/**
* Creates a {@link ServiceBusMessageBatch} that can fit as many messages as the transport allows.
*
* @return A {@link ServiceBusMessageBatch} that can fit as many messages as the transport allows.
*
* @throws ServiceBusException if the message batch could not be created.
* @throws IllegalStateException if sender is already disposed.
*/
public ServiceBusMessageBatch createMessageBatch() {
return asyncClient.createMessageBatch().block(tryTimeout);
}
/**
* Creates an {@link ServiceBusMessageBatch} configured with the options specified.
*
* @param options A set of options used to configure the {@link ServiceBusMessageBatch}.
* @return A new {@link ServiceBusMessageBatch} configured with the given options.
*
* @throws NullPointerException if {@code options} is null.
* @throws ServiceBusException if the message batch could not be created.
* @throws IllegalStateException if sender is already disposed.
* @throws IllegalArgumentException if {@link CreateMessageBatchOptions#getMaximumSizeInBytes()} is larger than
* maximum allowed size.
*/
public ServiceBusMessageBatch createMessageBatch(CreateMessageBatchOptions options) {
Objects.requireNonNull(options, "'options' cannot be null.");
return asyncClient.createMessageBatch(options).block(tryTimeout);
}
/**
* Gets the name of the Service Bus resource.
*
* @return The name of the Service Bus resource.
*/
public String getEntityPath() {
return asyncClient.getEntityPath();
}
/**
* Gets the fully qualified namespace.
*
* @return The fully qualified namespace.
*/
public String getFullyQualifiedNamespace() {
return asyncClient.getFullyQualifiedNamespace();
}
/**
* Gets the identifier of the instance of {@link ServiceBusSenderClient}.
*
* @return The identifier that can identify the instance of {@link ServiceBusSenderClient}.
*/
public String getIdentifier() {
return asyncClient.getIdentifier();
}
/**
* Sends a message to a Service Bus queue or topic.
*
* @param message Message to be sent to Service Bus queue or topic.
*
* @throws NullPointerException if {@code message} is {@code null}.
* @throws ServiceBusException if {@code message} is larger than the maximum allowed size of a single message or
* the message could not be sent.
* @throws IllegalStateException if sender is already disposed.
*/
public void sendMessage(ServiceBusMessage message) {
Objects.requireNonNull(message, "'message' cannot be null.");
asyncClient.sendMessage(message).block(tryTimeout);
}
/**
* Sends a set of {@link ServiceBusMessage} to a Service Bus queue or topic using a batched approach.
* If the size of messages exceed the maximum size of a single batch, an exception will be triggered and the send
* will fail. By default, the message size is the max amount allowed on the link.
*
* @param messages Messages to be sent to Service Bus queue or topic.
*
* @throws NullPointerException if {@code messages} is {@code null}.
* @throws ServiceBusException if the message could not be sent or {@code message} is larger than the maximum size of the {@link
* ServiceBusMessageBatch}.
* @throws IllegalStateException if sender is already disposed.
*/
public void sendMessages(Iterable<ServiceBusMessage> messages) {
asyncClient.sendMessages(messages).block(tryTimeout);
}
/**
* Sends a message batch to the Azure Service Bus entity this sender is connected to.
*
* @param batch of messages which allows client to send maximum allowed size for a batch of messages.
*
* @throws NullPointerException if {@code batch} is {@code null}.
* @throws IllegalStateException if sender is already disposed.
* @throws ServiceBusException if the message batch could not be sent.
*/
public void sendMessages(ServiceBusMessageBatch batch) {
Objects.requireNonNull(batch, "'batch' cannot be null.");
asyncClient.sendMessages(batch).block(tryTimeout);
}
/**
* Sends a message to a Service Bus queue or topic.
*
* @param message Message to be sent to Service Bus queue or topic.
* @param transactionContext to be set on message before sending to Service Bus.
*
* @throws NullPointerException if {@code message}, {@code transactionContext} or
* {@code transactionContext.transactionId} is {@code null}.
* @throws ServiceBusException if {@code message} is larger than the maximum allowed size of a single message or
* the message could not be sent.
* @throws IllegalStateException if sender is already disposed.
*/
public void sendMessage(ServiceBusMessage message, ServiceBusTransactionContext transactionContext) {
asyncClient.sendMessage(message, transactionContext).block(tryTimeout);
}
/**
* Sends a set of {@link ServiceBusMessage} to a Service Bus queue or topic using a batched approach.
* If the size of messages exceed the maximum size of a single batch, an exception will be triggered and the send
* will fail. By default, the message size is the max amount allowed on the link.
*
* @param messages Messages to be sent to Service Bus queue or topic.
* @param transactionContext to be set on message before sending to Service Bus.
*
* @throws NullPointerException if {@code messages}, {@code transactionContext} or
* {@code transactionContext.transactionId} is {@code null}.
* @throws ServiceBusException if the message could not be sent or {@code message} is larger than the maximum size of the {@link
* ServiceBusMessageBatch}.
* @throws IllegalStateException if sender is already disposed.
*/
public void sendMessages(Iterable<ServiceBusMessage> messages, ServiceBusTransactionContext transactionContext) {
asyncClient.sendMessages(messages, transactionContext).block(tryTimeout);
}
/**
* Sends a message batch to the Azure Service Bus entity this sender is connected to.
*
* @param batch of messages which allows client to send maximum allowed size for a batch of messages.
* @param transactionContext to be set on message before sending to Service Bus.
*
* @throws NullPointerException if {@code batch}, {@code transactionContext} or
* {@code transactionContext.transactionId} is {@code null}.
* @throws ServiceBusException if message batch could not be sent.
* @throws IllegalStateException if sender is already disposed.
*/
public void sendMessages(ServiceBusMessageBatch batch, ServiceBusTransactionContext transactionContext) {
asyncClient.sendMessages(batch, transactionContext).block(tryTimeout);
}
/**
* Sends a scheduled message to the Azure Service Bus entity this sender is connected to. A scheduled message is
* enqueued and made available to receivers only at the scheduled enqueue time.
*
* @param message Message to be sent to the Service Bus Queue or Topic.
* @param scheduledEnqueueTime Datetime at which the message should appear in the Service Bus queue or topic.
*
* @return The sequence number of the scheduled message which can be used to cancel the scheduling of the message.
*
* @throws NullPointerException if {@code message} or {@code scheduledEnqueueTime} is {@code null}.
* @throws ServiceBusException If the message could not be scheduled.
* @throws IllegalStateException if sender is already disposed.
*/
public Long scheduleMessage(ServiceBusMessage message, OffsetDateTime scheduledEnqueueTime) {
return asyncClient.scheduleMessage(message, scheduledEnqueueTime).block(tryTimeout);
}
/**
* Sends a scheduled message to the Azure Service Bus entity this sender is connected to. A scheduled message is
* enqueued and made available to receivers only at the scheduled enqueue time.
*
* @param message Message to be sent to the Service Bus Queue or Topic.
* @param scheduledEnqueueTime Datetime at which the message should appear in the Service Bus queue or topic.
* @param transactionContext to be set on message before sending to Service Bus.
*
* @return The sequence number of the scheduled message which can be used to cancel the scheduling of the message.
*
* @throws IllegalStateException if sender is already disposed.
* @throws NullPointerException if {@code message}, {@code scheduledEnqueueTime}, {@code transactionContext} or
* {@code transactionContext.transactionId} is {@code null}.
* @throws ServiceBusException If the message could not be scheduled.
*/
public Long scheduleMessage(ServiceBusMessage message, OffsetDateTime scheduledEnqueueTime,
ServiceBusTransactionContext transactionContext) {
return asyncClient.scheduleMessage(message, scheduledEnqueueTime, transactionContext).block(tryTimeout);
}
/**
* Sends a batch of scheduled messages to the Azure Service Bus entity this sender is connected to. A scheduled
* message is enqueued and made available to receivers only at the scheduled enqueue time.
*
* @param messages Messages to be sent to the Service Bus queue or topic.
* @param scheduledEnqueueTime Instant at which the message should appear in the Service Bus queue or topic.
*
* @return Sequence numbers of the scheduled messages which can be used to cancel the messages.
*
* @throws IllegalStateException if sender is already disposed.
* @throws NullPointerException If {@code messages} or {@code scheduledEnqueueTime} is {@code null}.
* @throws ServiceBusException If the messages could not be scheduled.
*/
public Iterable<Long> scheduleMessages(Iterable<ServiceBusMessage> messages, OffsetDateTime scheduledEnqueueTime) {
return new IterableStream<>(asyncClient.scheduleMessages(messages, scheduledEnqueueTime));
}
/**
* Sends a batch of scheduled messages to the Azure Service Bus entity this sender is connected to. A scheduled
* message is enqueued and made available to receivers only at the scheduled enqueue time.
*
* @param messages Messages to be sent to the Service Bus Queue or Topic.
* @param scheduledEnqueueTime Instant at which the message should appear in the Service Bus queue or topic.
* @param transactionContext Transaction to associate with the operation.
*
* @return Sequence numbers of the scheduled messages which can be used to cancel the messages.
*
* @throws IllegalStateException if sender is already disposed.
* @throws NullPointerException If {@code messages}, {@code scheduledEnqueueTime}, {@code transactionContext} or
* {@code transactionContext.transactionId} is {@code null}.
* @throws ServiceBusException If the messages could not be scheduled or the {@code message} is larger than
* the maximum size of the {@link ServiceBusMessageBatch}.
*/
public Iterable<Long> scheduleMessages(Iterable<ServiceBusMessage> messages, OffsetDateTime scheduledEnqueueTime,
ServiceBusTransactionContext transactionContext) {
return new IterableStream<>(asyncClient.scheduleMessages(messages, scheduledEnqueueTime, transactionContext));
}
/**
* Starts a new transaction on Service Bus. The {@link ServiceBusTransactionContext} should be passed along to all
* operations that need to be in this transaction.
*
* @return A new {@link ServiceBusTransactionContext}.
*
* @throws IllegalStateException if sender is already disposed.
* @throws ServiceBusException if a transaction cannot be created.
*
* @see ServiceBusReceiverClient#createTransaction()
*/
public ServiceBusTransactionContext createTransaction() {
return asyncClient.createTransaction().block(tryTimeout);
}
/**
* Commits the transaction given {@link ServiceBusTransactionContext}.
*
* @param transactionContext to be committed.
*
* @throws IllegalStateException if sender is already disposed.
* @throws NullPointerException if {@code transactionContext} or {@code transactionContext.transactionId} is null.
* @throws ServiceBusException if the transaction could not be committed.
*
* @see ServiceBusReceiverClient#commitTransaction(ServiceBusTransactionContext)
*/
public void commitTransaction(ServiceBusTransactionContext transactionContext) {
asyncClient.commitTransaction(transactionContext).block(tryTimeout);
}
/**
* Rollbacks the transaction given and all operations associated with it.
*
* @param transactionContext The transaction to rollback.
*
* @throws IllegalStateException if sender is already disposed.
* @throws NullPointerException if {@code transactionContext} or {@code transactionContext.transactionId} is null.
* @throws ServiceBusException if the transaction could not be rolled back.
*
* @see ServiceBusReceiverClient#rollbackTransaction(ServiceBusTransactionContext)
*/
public void rollbackTransaction(ServiceBusTransactionContext transactionContext) {
asyncClient.rollbackTransaction(transactionContext).block(tryTimeout);
}
/**
* Disposes of the {@link ServiceBusSenderClient}. If the client has a dedicated connection, the underlying
* connection is also closed.
*/
@Override
public void close() {
asyncClient.close();
}
}