Class ServiceBusSenderClient

java.lang.Object
com.azure.messaging.servicebus.ServiceBusSenderClient
All Implemented Interfaces:
AutoCloseable

public final class ServiceBusSenderClient extends Object implements AutoCloseable
A synchronous sender responsible for sending ServiceBusMessage to specific queue or topic on Azure Service Bus.

Create an instance of sender

 // The required parameters is connectionString, a way to authenticate with Service Bus using credentials.
 // The connectionString/queueName must be set by the application. The 'connectionString' format is shown below.
 // "Endpoint={fully-qualified-namespace};SharedAccessKeyName={policy-name};SharedAccessKey={key}"
 ServiceBusSenderClient sender = new ServiceBusClientBuilder()
     .connectionString(connectionString)
     .sender()
     .queueName(queueName)
     .buildClient();
 

Send messages to a Service Bus resource

 List<ServiceBusMessage> messages = Arrays.asList(new ServiceBusMessage(BinaryData.fromBytes("test-1".getBytes(UTF_8))),
     new ServiceBusMessage(BinaryData.fromBytes("test-2".getBytes(UTF_8))));

 CreateMessageBatchOptions options = new CreateMessageBatchOptions().setMaximumSizeInBytes(10 * 1024);

 // Creating a batch without options set.
 ServiceBusMessageBatch batch = sender.createMessageBatch(options);
 for (ServiceBusMessage message : messages) {
     if (batch.tryAddMessage(message)) {
         continue;
     }

     sender.sendMessages(batch);
 }
 

Send messages using a size-limited ServiceBusMessageBatch

 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.");
         }
     }
 }
 
See Also: