Skip to content

Commit 13a1999

Browse files
authored
Merge pull request #234330 from spelluru/sbuspwless
Added passwordless option to Service Bus quickstarts
2 parents d9324e7 + c09e055 commit 13a1999

File tree

3 files changed

+470
-62
lines changed

3 files changed

+470
-62
lines changed

articles/service-bus-messaging/service-bus-java-how-to-use-queues.md

Lines changed: 235 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
---
22
title: Get started with Azure Service Bus queues (Java)
33
description: This tutorial shows you how to send messages to and receive messages from Azure Service Bus queues using the Java programming language.
4-
ms.date: 03/24/2022
4+
ms.date: 04/12/2023
55
ms.topic: quickstart
66
ms.devlang: java
77
ms.custom: seo-java-july2019, seo-java-august2019, seo-java-september2019, devx-track-java, mode-api
@@ -14,7 +14,7 @@ ms.custom: seo-java-july2019, seo-java-august2019, seo-java-september2019, devx-
1414
> * [JavaScript](service-bus-nodejs-how-to-use-queues.md)
1515
> * [Python](service-bus-python-how-to-use-queues.md)
1616
17-
In this quickstart, you'll create a Java app to send messages to and receive messages from an Azure Service Bus queue.
17+
In this quickstart, you create a Java app to send messages to and receive messages from an Azure Service Bus queue.
1818

1919
> [!NOTE]
2020
> This quick start provides step-by-step instructions for a simple scenario of sending messages to a Service Bus queue and receiving them. You can find pre-built Java samples for Azure Service Bus in the [Azure SDK for Java repository on GitHub](https://github.com/azure/azure-sdk-for-java/tree/main/sdk/servicebus/azure-messaging-servicebus/src/samples).
@@ -24,52 +24,76 @@ In this quickstart, you'll create a Java app to send messages to and receive mes
2424
2525
## Prerequisites
2626
- An Azure subscription. To complete this tutorial, you need an Azure account. You can activate your [MSDN subscriber benefits](https://azure.microsoft.com/pricing/member-offers/credit-for-visual-studio-subscribers/?WT.mc_id=A85619ABF) or sign up for a [free account](https://azure.microsoft.com/free/?WT.mc_id=A85619ABF).
27-
- If you don't have a queue to work with, follow steps in the [Use Azure portal to create a Service Bus queue](service-bus-quickstart-portal.md) article to create a queue. Note down the **connection string** for your Service Bus namespace and the name of the **queue** you created.
2827
- Install [Azure SDK for Java][Azure SDK for Java]. If you're using Eclipse, you can install the [Azure Toolkit for Eclipse][Azure Toolkit for Eclipse] that includes the Azure SDK for Java. You can then add the **Microsoft Azure Libraries for Java** to your project. If you're using IntelliJ, see [Install the Azure Toolkit for IntelliJ](/azure/developer/java/toolkit-for-intellij/installation).
2928

29+
[!INCLUDE [service-bus-create-namespace-portal](./includes/service-bus-create-namespace-portal.md)]
30+
31+
[!INCLUDE [service-bus-create-queue-portal](./includes/service-bus-create-queue-portal.md)]
32+
33+
[!INCLUDE [service-bus-passwordless-template-tabbed](../../includes/passwordless/service-bus/service-bus-passwordless-template-tabbed.md)]
34+
3035

3136
## Send messages to a queue
32-
In this section, you'll create a Java console project, and add code to send messages to the queue that you created earlier.
37+
In this section, you create a Java console project, and add code to send messages to the queue that you created earlier.
3338

3439
### Create a Java console project
3540
Create a Java project using Eclipse or a tool of your choice.
3641

3742
### Configure your application to use Service Bus
3843
Add references to Azure Core and Azure Service Bus libraries.
3944

40-
If you are using Eclipse and created a Java console application, convert your Java project to a Maven: right-click the project in the **Package Explorer** window, select **Configure** -> **Convert to Maven project**. Then, add dependencies to these two libraries as shown in the following example.
45+
If you're using Eclipse and created a Java console application, convert your Java project to a Maven: right-click the project in the **Package Explorer** window, select **Configure** -> **Convert to Maven project**. Then, add dependencies to these two libraries as shown in the following example.
46+
47+
48+
### [Passwordless (Recommended)](#tab/passwordless)
49+
Update the `pom.xml` file to add dependencies to Azure Service Bus and Azure Identity packages.
4150

4251
```xml
43-
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
44-
<modelVersion>4.0.0</modelVersion>
45-
<groupId>org.myorg.sbusquickstarts</groupId>
46-
<artifactId>sbustopicqs</artifactId>
47-
<version>0.0.1-SNAPSHOT</version>
48-
<build>
49-
<sourceDirectory>src</sourceDirectory>
50-
<plugins>
51-
<plugin>
52-
<artifactId>maven-compiler-plugin</artifactId>
53-
<version>3.8.1</version>
54-
<configuration>
55-
<release>15</release>
56-
</configuration>
57-
</plugin>
58-
</plugins>
59-
</build>
60-
<dependencies>
52+
<dependencies>
6153
<dependency>
6254
<groupId>com.azure</groupId>
6355
<artifactId>azure-messaging-servicebus</artifactId>
64-
<version>7.7.0</version>
56+
<version>7.13.3</version>
6557
</dependency>
66-
</dependencies>
67-
</project>
58+
<dependency>
59+
<groupId>com.azure</groupId>
60+
<artifactId>azure-identity</artifactId>
61+
<version>1.8.0</version>
62+
<scope>compile</scope>
63+
</dependency>
64+
</dependencies>
6865
```
6966

67+
### [Connection String](#tab/connection-string)
68+
Update the `pom.xml` file to add a dependency to the Azure Service Bus package.
69+
70+
```xml
71+
<dependency>
72+
<groupId>com.azure</groupId>
73+
<artifactId>azure-messaging-servicebus</artifactId>
74+
<version>7.13.3</version>
75+
</dependency>
76+
```
77+
---
78+
7079
### Add code to send messages to the queue
80+
7181
1. Add the following `import` statements at the topic of the Java file.
7282

83+
### [Passwordless (Recommended)](#tab/passwordless)
84+
85+
```java
86+
import com.azure.messaging.servicebus.*;
87+
import com.azure.identity.*;
88+
89+
import java.util.concurrent.CountDownLatch;
90+
import java.util.concurrent.TimeUnit;
91+
import java.util.Arrays;
92+
import java.util.List;
93+
```
94+
95+
### [Connection String](#tab/connection-string)
96+
7397
```java
7498
import com.azure.messaging.servicebus.*;
7599

@@ -78,16 +102,61 @@ If you are using Eclipse and created a Java console application, convert your Ja
78102
import java.util.Arrays;
79103
import java.util.List;
80104
```
81-
5. In the class, define variables to hold connection string and queue name as shown below:
105+
---
106+
2. In the class, define variables to hold connection string and queue name.
107+
108+
### [Passwordless (Recommended)](#tab/passwordless)
109+
110+
```java
111+
static String queueName = "<QUEUE NAME>";
112+
```
113+
114+
> [!IMPORTANT]
115+
> Replace `<QUEUE NAME>` with the name of the queue.
116+
117+
### [Connection String](#tab/connection-string)
82118

83119
```java
84120
static String connectionString = "<NAMESPACE CONNECTION STRING>";
85121
static String queueName = "<QUEUE NAME>";
86122
```
87123

88-
Replace `<NAMESPACE CONNECTION STRING>` with the connection string to your Service Bus namespace. And, replace `<QUEUE NAME>` with the name of the queue.
124+
> [!IMPORTANT]
125+
> Replace `<NAMESPACE CONNECTION STRING>` with the connection string to your Service Bus namespace, and `<QUEUE NAME>` with the name of the queue.
126+
127+
---
89128
3. Add a method named `sendMessage` in the class to send one message to the queue.
90129

130+
### [Passwordless (Recommended)](#tab/passwordless)
131+
132+
> [!IMPORTANT]
133+
> - Replace `NAMESPACENAME` with the name of your Service Bus namespace.
134+
> - This sample uses `AZURE_PUBLIC_CLOUD` as the authority host. For supported authority hosts, see [`AzureAuthorityHosts`](/dotnet/api/azure.identity.azureauthorityhosts)
135+
136+
```java
137+
static void sendMessage()
138+
{
139+
// create a token using the default Azure credential
140+
DefaultAzureCredential credential = new DefaultAzureCredentialBuilder()
141+
.authorityHost(AzureAuthorityHosts.AZURE_PUBLIC_CLOUD)
142+
.build();
143+
144+
ServiceBusSenderClient senderClient = new ServiceBusClientBuilder()
145+
.fullyQualifiedNamespace("NAMESPACENAME.servicebus.windows.net")
146+
.credential(credential)
147+
.sender()
148+
.queueName(queueName)
149+
.buildClient();
150+
151+
// send one message to the queue
152+
senderClient.sendMessage(new ServiceBusMessage("Hello, World!"));
153+
System.out.println("Sent a single message to the queue: " + queueName);
154+
}
155+
156+
```
157+
158+
### [Connection String](#tab/connection-string)
159+
91160
```java
92161
static void sendMessage()
93162
{
@@ -103,7 +172,8 @@ If you are using Eclipse and created a Java console application, convert your Ja
103172
System.out.println("Sent a single message to the queue: " + queueName);
104173
}
105174
```
106-
1. Add a method named `createMessages` in the class to create a list of messages. Typically, you get these messages from different parts of your application. Here, we create a list of sample messages.
175+
---
176+
4. Add a method named `createMessages` in the class to create a list of messages. Typically, you get these messages from different parts of your application. Here, we create a list of sample messages.
107177

108178
```java
109179
static List<ServiceBusMessage> createMessages()
@@ -117,8 +187,69 @@ If you are using Eclipse and created a Java console application, convert your Ja
117187
return Arrays.asList(messages);
118188
}
119189
```
120-
1. Add a method named `sendMessageBatch` method to send messages to the queue you created. This method creates a `ServiceBusSenderClient` for the queue, invokes the `createMessages` method to get the list of messages, prepares one or more batches, and sends the batches to the queue.
190+
5. Add a method named `sendMessageBatch` method to send messages to the queue you created. This method creates a `ServiceBusSenderClient` for the queue, invokes the `createMessages` method to get the list of messages, prepares one or more batches, and sends the batches to the queue.
191+
192+
### [Passwordless (Recommended)](#tab/passwordless)
193+
194+
> [!IMPORTANT]
195+
> - Replace `NAMESPACENAME` with the name of your Service Bus namespace.
196+
> - This sample uses `AZURE_PUBLIC_CLOUD` as the authority host. For supported authority hosts, see [`AzureAuthorityHosts`](/dotnet/api/azure.identity.azureauthorityhosts)
197+
121198

199+
```java
200+
static void sendMessageBatch()
201+
{
202+
// create a token using the default Azure credential
203+
DefaultAzureCredential credential = new DefaultAzureCredentialBuilder()
204+
.authorityHost(AzureAuthorityHosts.AZURE_PUBLIC_CLOUD)
205+
.build();
206+
207+
ServiceBusSenderClient senderClient = new ServiceBusClientBuilder()
208+
.fullyQualifiedNamespace("NAMESPACENAME.servicebus.windows.net")
209+
.credential(credential)
210+
.sender()
211+
.queueName(queueName)
212+
.buildClient();
213+
214+
// Creates an ServiceBusMessageBatch where the ServiceBus.
215+
ServiceBusMessageBatch messageBatch = senderClient.createMessageBatch();
216+
217+
// create a list of messages
218+
List<ServiceBusMessage> listOfMessages = createMessages();
219+
220+
// We try to add as many messages as a batch can fit based on the maximum size and send to Service Bus when
221+
// the batch can hold no more messages. Create a new batch for next set of messages and repeat until all
222+
// messages are sent.
223+
for (ServiceBusMessage message : listOfMessages) {
224+
if (messageBatch.tryAddMessage(message)) {
225+
continue;
226+
}
227+
228+
// The batch is full, so we create a new batch and send the batch.
229+
senderClient.sendMessages(messageBatch);
230+
System.out.println("Sent a batch of messages to the queue: " + queueName);
231+
232+
// create a new batch
233+
messageBatch = senderClient.createMessageBatch();
234+
235+
// Add that message that we couldn't before.
236+
if (!messageBatch.tryAddMessage(message)) {
237+
System.err.printf("Message is too large for an empty batch. Skipping. Max size: %s.", messageBatch.getMaxSizeInBytes());
238+
}
239+
}
240+
241+
if (messageBatch.getCount() > 0) {
242+
senderClient.sendMessages(messageBatch);
243+
System.out.println("Sent a batch of messages to the queue: " + queueName);
244+
}
245+
246+
//close the client
247+
senderClient.close();
248+
}
249+
```
250+
251+
### [Connection String](#tab/connection-string)
252+
122253
```java
123254
static void sendMessageBatch()
124255
{
@@ -166,11 +297,51 @@ If you are using Eclipse and created a Java console application, convert your Ja
166297
}
167298
```
168299

300+
---
301+
169302
## Receive messages from a queue
170-
In this section, you'll add code to retrieve messages from the queue.
303+
In this section, you add code to retrieve messages from the queue.
171304

172305
1. Add a method named `receiveMessages` to receive messages from the queue. This method creates a `ServiceBusProcessorClient` for the queue by specifying a handler for processing messages and another one for handling errors. Then, it starts the processor, waits for few seconds, prints the messages that are received, and then stops and closes the processor.
173306

307+
### [Passwordless (Recommended)](#tab/passwordless)
308+
309+
> [!IMPORTANT]
310+
> - Replace `NAMESPACENAME` with the name of your Service Bus namespace.
311+
> - Replace `QueueTest` in `QueueTest::processMessage` in the code with the name of your class.
312+
> - This sample uses `AZURE_PUBLIC_CLOUD` as the authority host. For supported authority hosts, see [`AzureAuthorityHosts`](/dotnet/api/azure.identity.azureauthorityhosts)
313+
314+
315+
```java
316+
// handles received messages
317+
static void receiveMessages() throws InterruptedException
318+
{
319+
CountDownLatch countdownLatch = new CountDownLatch(1);
320+
321+
DefaultAzureCredential credential = new DefaultAzureCredentialBuilder()
322+
.authorityHost(AzureAuthorityHosts.AZURE_PUBLIC_CLOUD)
323+
.build();
324+
325+
ServiceBusProcessorClient processorClient = new ServiceBusClientBuilder()
326+
.fullyQualifiedNamespace("NAMESPACENAME.servicebus.windows.net")
327+
.credential(credential)
328+
.processor()
329+
.queueName(queueName)
330+
.processMessage(QueueTest::processMessage)
331+
.processError(context -> processError(context, countdownLatch))
332+
.buildProcessorClient();
333+
334+
System.out.println("Starting the processor");
335+
processorClient.start();
336+
337+
TimeUnit.SECONDS.sleep(10);
338+
System.out.println("Stopping and closing the processor");
339+
processorClient.close();
340+
}
341+
```
342+
343+
### [Connection String](#tab/connection-string)
344+
174345
> [!IMPORTANT]
175346
> Replace `QueueTest` in `QueueTest::processMessage` in the code with the name of your class.
176347

@@ -197,6 +368,7 @@ In this section, you'll add code to retrieve messages from the queue.
197368
processorClient.close();
198369
}
199370
```
371+
---
200372
2. Add the `processMessage` method to process a message received from the Service Bus subscription.
201373

202374
```java
@@ -254,6 +426,37 @@ In this section, you'll add code to retrieve messages from the queue.
254426
```
255427

256428
## Run the app
429+
430+
### [Passwordless (Recommended)](#tab/passwordless)
431+
432+
1. If you're using Eclipse, right-click the project, select **Export**, expand **Java**, select **Runnable JAR file**, and follow the steps to create a runnable JAR file.
433+
1. If you are signed into the machine using a user account that's different from the user account added to the **Azure Service Bus Data Owner** role, follow these steps. Otherwise, skip this step and move on to run the Jar file in the next step.
434+
435+
1. [Install Azure CLI](/cli/azure/install-azure-cli-windows) on your machine.
436+
1. Run the following CLI command to sign in to Azure. Use the same user account that you added to the **Azure Service Bus Data Owner** role.
437+
438+
```azurecli
439+
az login
440+
```
441+
1. Run the Jar file using the following command.
442+
443+
```java
444+
java -jar <JAR FILE NAME>
445+
```
446+
1. You see the following output in the console window.
447+
448+
```console
449+
Sent a single message to the queue: myqueue
450+
Sent a batch of messages to the queue: myqueue
451+
Starting the processor
452+
Processing message. Session: 88d961dd801f449e9c3e0f8a5393a527, Sequence #: 1. Contents: Hello, World!
453+
Processing message. Session: e90c8d9039ce403bbe1d0ec7038033a0, Sequence #: 2. Contents: First message
454+
Processing message. Session: 311a216a560c47d184f9831984e6ac1d, Sequence #: 3. Contents: Second message
455+
Processing message. Session: f9a871be07414baf9505f2c3d466c4ab, Sequence #: 4. Contents: Third message
456+
Stopping and closing the processor
457+
```
458+
459+
### [Connection String](#tab/connection-string)
257460
When you run the application, you see the following messages in the console window.
258461

259462
```console
@@ -266,6 +469,7 @@ Processing message. Session: 311a216a560c47d184f9831984e6ac1d, Sequence #: 3. Co
266469
Processing message. Session: f9a871be07414baf9505f2c3d466c4ab, Sequence #: 4. Contents: Third message
267470
Stopping and closing the processor
268471
```
472+
---
269473

270474
On the **Overview** page for the Service Bus namespace in the Azure portal, you can see **incoming** and **outgoing** message count. You may need to wait for a minute or so and then refresh the page to see the latest values.
271475

0 commit comments

Comments
 (0)