ServiceBusSenderClient Class

  • java.lang.Object
    • com.azure.messaging.servicebus.ServiceBusSenderClient

Implements

public final class ServiceBusSenderClient
implements AutoCloseable

A synchronous sender responsible for sending ServiceBusMessage to a queue or topic on Azure Service Bus.

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 managed identity for authentication in production environments. You can find more information on different ways of authenticating and their corresponding credential types in the Azure Identity documentation".

Sample: Create an instance of sender

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"));

Sample: Send messages to a Service Bus resource

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();

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

 // 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();

Sample: Sending a message to a session-enabled queue

The snippet below demonstrates sending a message to a Service Bus sessions enabled queue. Setting setMessageId(String messageId) property to "greetings" will send the message to a Service Bus session with an id of "greetings".

// '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();

Method Summary

Modifier and Type Method and Description
void cancelScheduledMessage(long sequenceNumber)

Cancels the enqueuing of a scheduled message, if they are not already enqueued.

void cancelScheduledMessages(Iterable<Long> sequenceNumbers)

Cancels the enqueuing of scheduled messages, if they are not already enqueued.

void close()

Disposes of the ServiceBusSenderClient.

void commitTransaction(ServiceBusTransactionContext transactionContext)

Commits the transaction given ServiceBusTransactionContext.

ServiceBusMessageBatch createMessageBatch()

Creates a ServiceBusMessageBatch that can fit as many messages as the transport allows.

ServiceBusMessageBatch createMessageBatch(CreateMessageBatchOptions options)

Creates an ServiceBusMessageBatch configured with the options specified.

ServiceBusTransactionContext createTransaction()

Starts a new transaction on Service Bus.

String getEntityPath()

Gets the name of the Service Bus resource.

String getFullyQualifiedNamespace()

Gets the fully qualified namespace.

String getIdentifier()

Gets the identifier of the instance of ServiceBusSenderClient.

void rollbackTransaction(ServiceBusTransactionContext transactionContext)

Rollbacks the transaction given and all operations associated with it.

Long scheduleMessage(ServiceBusMessage message, OffsetDateTime scheduledEnqueueTime)

Sends a scheduled message to the Azure Service Bus entity this sender is connected to.

Long scheduleMessage(ServiceBusMessage message, OffsetDateTime scheduledEnqueueTime, ServiceBusTransactionContext transactionContext)

Sends a scheduled message to the Azure Service Bus entity this sender is connected to.

Iterable<Long> scheduleMessages(Iterable<ServiceBusMessage> messages, OffsetDateTime scheduledEnqueueTime)

Sends a batch of scheduled messages to the Azure Service Bus entity this sender is connected to.

Iterable<Long> scheduleMessages(Iterable<ServiceBusMessage> messages, OffsetDateTime scheduledEnqueueTime, ServiceBusTransactionContext transactionContext)

Sends a batch of scheduled messages to the Azure Service Bus entity this sender is connected to.

void sendMessage(ServiceBusMessage message)

Sends a message to a Service Bus queue or topic.

void sendMessage(ServiceBusMessage message, ServiceBusTransactionContext transactionContext)

Sends a message to a Service Bus queue or topic.

void sendMessages(ServiceBusMessageBatch batch)

Sends a message batch to the Azure Service Bus entity this sender is connected to.

void sendMessages(ServiceBusMessageBatch batch, ServiceBusTransactionContext transactionContext)

Sends a message batch to the Azure Service Bus entity this sender is connected to.

void sendMessages(Iterable<ServiceBusMessage> messages)

Sends a set of ServiceBusMessage to a Service Bus queue or topic using a batched approach.

void sendMessages(Iterable<ServiceBusMessage> messages, ServiceBusTransactionContext transactionContext)

Sends a set of ServiceBusMessage to a Service Bus queue or topic using a batched approach.

Methods inherited from java.lang.Object

Method Details

cancelScheduledMessage

public void cancelScheduledMessage(long sequenceNumber)

Cancels the enqueuing of a scheduled message, if they are not already enqueued.

Parameters:

sequenceNumber - The sequence number of the message to cancel.

cancelScheduledMessages

public void cancelScheduledMessages(Iterable sequenceNumbers)

Cancels the enqueuing of scheduled messages, if they are not already enqueued.

Parameters:

sequenceNumbers - The sequence numbers of messages to cancel.

close

public void close()

Disposes of the ServiceBusSenderClient. If the client has a dedicated connection, the underlying connection is also closed.

commitTransaction

public void commitTransaction(ServiceBusTransactionContext transactionContext)

Commits the transaction given ServiceBusTransactionContext.

Parameters:

transactionContext - to be committed.

createMessageBatch

public ServiceBusMessageBatch createMessageBatch()

Creates a ServiceBusMessageBatch that can fit as many messages as the transport allows.

Returns:

A ServiceBusMessageBatch that can fit as many messages as the transport allows.

createMessageBatch

public ServiceBusMessageBatch createMessageBatch(CreateMessageBatchOptions options)

Creates an ServiceBusMessageBatch configured with the options specified.

Parameters:

options - A set of options used to configure the ServiceBusMessageBatch.

Returns:

A new ServiceBusMessageBatch configured with the given options.

createTransaction

public ServiceBusTransactionContext createTransaction()

Starts a new transaction on Service Bus. The ServiceBusTransactionContext should be passed along to all operations that need to be in this transaction.

Returns:

getEntityPath

public String getEntityPath()

Gets the name of the Service Bus resource.

Returns:

The name of the Service Bus resource.

getFullyQualifiedNamespace

public String getFullyQualifiedNamespace()

Gets the fully qualified namespace.

Returns:

The fully qualified namespace.

getIdentifier

public String getIdentifier()

Gets the identifier of the instance of ServiceBusSenderClient.

Returns:

The identifier that can identify the instance of ServiceBusSenderClient.

rollbackTransaction

public void rollbackTransaction(ServiceBusTransactionContext transactionContext)

Rollbacks the transaction given and all operations associated with it.

Parameters:

transactionContext - The transaction to rollback.

scheduleMessage

public Long scheduleMessage(ServiceBusMessage message, OffsetDateTime scheduledEnqueueTime)

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.

Parameters:

message - Message to be sent to the Service Bus Queue or Topic.
scheduledEnqueueTime - Datetime at which the message should appear in the Service Bus queue or topic.

Returns:

The sequence number of the scheduled message which can be used to cancel the scheduling of the message.

scheduleMessage

public Long scheduleMessage(ServiceBusMessage message, OffsetDateTime scheduledEnqueueTime, ServiceBusTransactionContext transactionContext)

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.

Parameters:

message - Message to be sent to the Service Bus Queue or Topic.
scheduledEnqueueTime - Datetime at which the message should appear in the Service Bus queue or topic.
transactionContext - to be set on message before sending to Service Bus.

Returns:

The sequence number of the scheduled message which can be used to cancel the scheduling of the message.

scheduleMessages

public Iterable scheduleMessages(Iterable messages, OffsetDateTime 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.

Parameters:

messages - Messages to be sent to the Service Bus queue or topic.
scheduledEnqueueTime - Instant at which the message should appear in the Service Bus queue or topic.

Returns:

Sequence numbers of the scheduled messages which can be used to cancel the messages.

scheduleMessages

public Iterable scheduleMessages(Iterable messages, OffsetDateTime scheduledEnqueueTime, ServiceBusTransactionContext transactionContext)

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.

Parameters:

messages - Messages to be sent to the Service Bus Queue or Topic.
scheduledEnqueueTime - Instant at which the message should appear in the Service Bus queue or topic.
transactionContext - Transaction to associate with the operation.

Returns:

Sequence numbers of the scheduled messages which can be used to cancel the messages.

sendMessage

public void sendMessage(ServiceBusMessage message)

Sends a message to a Service Bus queue or topic.

Parameters:

message - Message to be sent to Service Bus queue or topic.

sendMessage

public void sendMessage(ServiceBusMessage message, ServiceBusTransactionContext transactionContext)

Sends a message to a Service Bus queue or topic.

Parameters:

message - Message to be sent to Service Bus queue or topic.
transactionContext - to be set on message before sending to Service Bus.

sendMessages

public void sendMessages(ServiceBusMessageBatch batch)

Sends a message batch to the Azure Service Bus entity this sender is connected to.

Parameters:

batch - of messages which allows client to send maximum allowed size for a batch of messages.

sendMessages

public void sendMessages(ServiceBusMessageBatch batch, ServiceBusTransactionContext transactionContext)

Sends a message batch to the Azure Service Bus entity this sender is connected to.

Parameters:

batch - of messages which allows client to send maximum allowed size for a batch of messages.
transactionContext - to be set on message before sending to Service Bus.

sendMessages

public void sendMessages(Iterable messages)

Sends a set of 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.

Parameters:

messages - Messages to be sent to Service Bus queue or topic.

sendMessages

public void sendMessages(Iterable messages, ServiceBusTransactionContext transactionContext)

Sends a set of 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.

Parameters:

messages - Messages to be sent to Service Bus queue or topic.
transactionContext - to be set on message before sending to Service Bus.

Applies to