Skip to content

Commit 2cf7674

Browse files
Merge pull request #218833 from diberry/azure-docs-pr-passwordless-servicebus-quickstart
Service Bus queues quickstart JS - passwordless
2 parents 888fc41 + a33ff95 commit 2cf7674

File tree

1 file changed

+268
-29
lines changed

1 file changed

+268
-29
lines changed

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

Lines changed: 268 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ title: Get started with Azure Service Bus queues (JavaScript)
33
description: This tutorial shows you how to send messages to and receive messages from Azure Service Bus queues using the JavaScript programming language.
44
author: spelluru
55
ms.author: spelluru
6-
ms.date: 02/16/2022
6+
ms.date: 11/17/2022
77
ms.topic: quickstart
88
ms.devlang: javascript
99
ms.custom: devx-track-js, mode-api
@@ -16,30 +16,185 @@ ms.custom: devx-track-js, mode-api
1616
> * [JavaScript](service-bus-nodejs-how-to-use-queues.md)
1717
> * [Python](service-bus-python-how-to-use-queues.md)
1818
19-
In this tutorial, you learn how to use the [@azure/service-bus](https://www.npmjs.com/package/@azure/service-bus) package in a JavaScript program to send messages to and receive messages from a Service Bus queue.
19+
In this tutorial, you complete the following steps:
20+
21+
1. Create a Service Bus namespace, using the Azure portal.
22+
2. Create a Service Bus queue, using the Azure portal.
23+
3. Write a JavaScript application to use the [@azure/service-bus](https://www.npmjs.com/package/@azure/service-bus) package to:
24+
1. Send a set of messages to the queue.
25+
1. Write a .NET console application to receive those messages from the queue.
2026

2127
> [!NOTE]
2228
> 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 JavaScript and TypeScript samples for Azure Service Bus in the [Azure SDK for JavaScript repository on GitHub](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/servicebus/service-bus/samples/v7).
2329
2430
## Prerequisites
31+
32+
If you're new to the service, see [Service Bus overview](service-bus-messaging-overview.md) before you do this quickstart.
33+
2534
- 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).
26-
- 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.
35+
- [Node.js LTS](https://nodejs.org/en/download/)
36+
- 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.
37+
38+
### [Passwordless](#tab/passwordless)
39+
40+
To use this quickstart with your own Azure account, you need:
41+
* Install [Azure CLI](/cli/azure/install-azure-cli), which provides the passwordless authentication to your developer machine.
42+
* Sign in with your Azure account at the terminal or command prompt with `az login`.
43+
* Use the same account when you add the appropriate data role to your resource.
44+
* Run the code in the same terminal or command prompt.
45+
* Note down your **queue** name for your Service Bus namespace. You'll need that in the code.
46+
47+
### [Connection string](#tab/connection-string)
48+
49+
Note down the following, which you'll use in the code below:
50+
* Service Bus namespace **connection string**
51+
* Service Bus namespace **queue** you created
52+
53+
---
2754

2855
> [!NOTE]
2956
> - This tutorial works with samples that you can copy and run using [Nodejs](https://nodejs.org/). For instructions on how to create a Node.js application, see [Create and deploy a Node.js application to an Azure Website](../app-service/quickstart-nodejs.md), or [Node.js cloud service using Windows PowerShell](../cloud-services/cloud-services-nodejs-develop-deploy-app.md).
3057
31-
### Use Node Package Manager (NPM) to install the package
32-
To install the npm package for Service Bus, open a command prompt that has `npm` in its path, change the directory to the folder where you want to have your samples and then run this command.
58+
[!INCLUDE [service-bus-create-namespace-portal](./includes/service-bus-create-namespace-portal.md)]
3359

34-
```bash
35-
npm install @azure/service-bus
36-
```
60+
[!INCLUDE [service-bus-create-queue-portal](./includes/service-bus-create-queue-portal.md)]
61+
62+
[!INCLUDE [service-bus-passwordless-template-tabbed](../../includes/passwordless/service-bus/service-bus-passwordless-template-tabbed.md)]
63+
64+
65+
## Use Node Package Manager (NPM) to install the package
66+
67+
### [Passwordless](#tab/passwordless)
68+
69+
1. To install the required npm package(s) for Service Bus, open a command prompt that has `npm` in its path, change the directory to the folder where you want to have your samples and then run this command.
70+
71+
1. Install the following packages:
72+
73+
```bash
74+
npm install @azure/service-bus @azure/identity
75+
```
76+
77+
### [Connection string](#tab/connection-string)
78+
79+
1. To install the required npm package(s) for Service Bus, open a command prompt that has `npm` in its path, change the directory to the folder where you want to have your samples and then run this command.
80+
81+
1. Install the following package:
82+
83+
```bash
84+
npm install @azure/service-bus
85+
```
86+
87+
---
3788

3889
## Send messages to a queue
39-
The following sample code shows you how to send a message to a queue.
90+
91+
The following sample code shows you how to send a message to a queue.
92+
93+
### [Passwordless](#tab/passwordless)
94+
95+
You must have signed in with the Azure CLI's `az login` in order for your local machine to provide the passwordless authentication required in this code.
96+
97+
1. Open your favorite editor, such as [Visual Studio Code](https://code.visualstudio.com/).
98+
1. Create a file called `send.js` and paste the below code into it. This code sends the names of scientists as messages to your queue.
99+
100+
The passwordless credential is provided with the [**DefaultAzureCredential**](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/identity/identity#defaultazurecredential).
101+
102+
```javascript
103+
const { ServiceBusClient } = require("@azure/service-bus");
104+
const { DefaultAzureCredential } = require("@azure/identity");
105+
106+
// Replace `<SERVICE-BUS-NAMESPACE>` with your namespace
107+
const fullyQualifiedNamespace = "<SERVICE-BUS-NAMESPACE>.servicebus.windows.net";
108+
109+
// Passwordless credential
110+
const credential = new DefaultAzureCredential();
111+
112+
// name of the queue
113+
const queueName = "<QUEUE NAME>"
114+
115+
const messages = [
116+
{ body: "Albert Einstein" },
117+
{ body: "Werner Heisenberg" },
118+
{ body: "Marie Curie" },
119+
{ body: "Steven Hawking" },
120+
{ body: "Isaac Newton" },
121+
{ body: "Niels Bohr" },
122+
{ body: "Michael Faraday" },
123+
{ body: "Galileo Galilei" },
124+
{ body: "Johannes Kepler" },
125+
{ body: "Nikolaus Kopernikus" }
126+
];
127+
128+
async function main() {
129+
// create a Service Bus client using the connection string to the Service Bus namespace
130+
const sbClient = new ServiceBusClient(fullyQualifiedNamespace, credential);
131+
132+
// createSender() can also be used to create a sender for a topic.
133+
const sender = sbClient.createSender(queueName);
134+
135+
try {
136+
// Tries to send all messages in a single batch.
137+
// Will fail if the messages cannot fit in a batch.
138+
// await sender.sendMessages(messages);
139+
140+
// create a batch object
141+
let batch = await sender.createMessageBatch();
142+
for (let i = 0; i < messages.length; i++) {
143+
// for each message in the array
144+
145+
// try to add the message to the batch
146+
if (!batch.tryAddMessage(messages[i])) {
147+
// if it fails to add the message to the current batch
148+
// send the current batch as it is full
149+
await sender.sendMessages(batch);
150+
151+
// then, create a new batch
152+
batch = await sender.createMessageBatch();
153+
154+
// now, add the message failed to be added to the previous batch to this batch
155+
if (!batch.tryAddMessage(messages[i])) {
156+
// if it still can't be added to the batch, the message is probably too big to fit in a batch
157+
throw new Error("Message too big to fit in a batch");
158+
}
159+
}
160+
}
161+
162+
// Send the last created batch of messages to the queue
163+
await sender.sendMessages(batch);
164+
165+
console.log(`Sent a batch of messages to the queue: ${queueName}`);
166+
167+
// Close the sender
168+
await sender.close();
169+
} finally {
170+
await sbClient.close();
171+
}
172+
}
173+
174+
// call the main function
175+
main().catch((err) => {
176+
console.log("Error occurred: ", err);
177+
process.exit(1);
178+
});
179+
```
180+
181+
3. Replace `<SERVICE-BUS-NAMESPACE>` with your Service Bus namespace.
182+
4. Replace `<QUEUE NAME>` with the name of the queue.
183+
5. Then run the command in a command prompt to execute this file.
184+
185+
```console
186+
node send.js
187+
```
188+
6. You should see the following output.
189+
190+
```console
191+
Sent a batch of messages to the queue: myqueue
192+
```
193+
194+
### [Connection string](#tab/connection-string)
40195
41196
1. Open your favorite editor, such as [Visual Studio Code](https://code.visualstudio.com/).
42-
2. Create a file called `send.js` and paste the below code into it. This code sends the names of scientists as messages to your queue.
197+
1. Create a file called `send.js` and paste the below code into it. This code sends the names of scientists as messages to your queue.
43198
44199
```javascript
45200
const { ServiceBusClient } = require("@azure/service-bus");
@@ -116,20 +271,87 @@ The following sample code shows you how to send a message to a queue.
116271
});
117272
```
118273
3. Replace `<CONNECTION STRING TO SERVICE BUS NAMESPACE>` with the connection string to your Service Bus namespace.
119-
1. Replace `<QUEUE NAME>` with the name of the queue.
120-
1. Then run the command in a command prompt to execute this file.
274+
4. Replace `<QUEUE NAME>` with the name of the queue.
275+
5. Then run the command in a command prompt to execute this file.
121276
122277
```console
123278
node send.js
124279
```
125-
1. You should see the following output.
280+
6. You should see the following output.
126281
127282
```console
128283
Sent a batch of messages to the queue: myqueue
129284
```
130285
286+
---
287+
131288
## Receive messages from a queue
132289
290+
### [Passwordless](#tab/passwordless)
291+
292+
You must have signed in with the Azure CLI's `az login` in order for your local machine to provide the passwordless authentication required in this code.
293+
294+
1. Open your favorite editor, such as [Visual Studio Code](https://code.visualstudio.com/)
295+
2. Create a file called `receive.js` and paste the following code into it.
296+
297+
```javascript
298+
const { delay, ServiceBusClient, ServiceBusMessage } = require("@azure/service-bus");
299+
const { DefaultAzureCredential } = require("@azure/identity");
300+
301+
// Replace `<SERVICE-BUS-NAMESPACE>` with your namespace
302+
const fullyQualifiedNamespace = "<SERVICE-BUS-NAMESPACE>.servicebus.windows.net";
303+
304+
// Passwordless credential
305+
const credential = new DefaultAzureCredential();
306+
307+
// name of the queue
308+
const queueName = "<QUEUE NAME>"
309+
310+
async function main() {
311+
// create a Service Bus client using the connection string to the Service Bus namespace
312+
const sbClient = new ServiceBusClient(fullyQualifiedNamespace, credential);
313+
314+
// createReceiver() can also be used to create a receiver for a subscription.
315+
const receiver = sbClient.createReceiver(queueName);
316+
317+
// function to handle messages
318+
const myMessageHandler = async (messageReceived) => {
319+
console.log(`Received message: ${messageReceived.body}`);
320+
};
321+
322+
// function to handle any errors
323+
const myErrorHandler = async (error) => {
324+
console.log(error);
325+
};
326+
327+
// subscribe and specify the message and error handlers
328+
receiver.subscribe({
329+
processMessage: myMessageHandler,
330+
processError: myErrorHandler
331+
});
332+
333+
// Waiting long enough before closing the sender to send messages
334+
await delay(20000);
335+
336+
await receiver.close();
337+
await sbClient.close();
338+
}
339+
// call the main function
340+
main().catch((err) => {
341+
console.log("Error occurred: ", err);
342+
process.exit(1);
343+
});
344+
```
345+
3. Replace `<SERVICE-BUS-NAMESPACE>` with your Service Bus namespace.
346+
4. Replace `<QUEUE NAME>` with the name of the queue.
347+
5. Then run the command in a command prompt to execute this file.
348+
349+
```console
350+
node receive.js
351+
```
352+
353+
### [Connection string](#tab/connection-string)
354+
133355
1. Open your favorite editor, such as [Visual Studio Code](https://code.visualstudio.com/)
134356
2. Create a file called `receive.js` and paste the following code into it.
135357
@@ -177,35 +399,52 @@ The following sample code shows you how to send a message to a queue.
177399
process.exit(1);
178400
});
179401
```
402+
180403
3. Replace `<CONNECTION STRING TO SERVICE BUS NAMESPACE>` with the connection string to your Service Bus namespace.
181-
1. Replace `<QUEUE NAME>` with the name of the queue.
182-
1. Then, run the command in a command prompt to execute this file.
183404
184-
```console
185-
node receive.js
186-
```
187-
1. You should see the following output.
405+
4. Replace `<QUEUE NAME>` with the name of the queue.
406+
5. Then run the command in a command prompt to execute this file.
188407
189408
```console
190-
Received message: Albert Einstein
191-
Received message: Werner Heisenberg
192-
Received message: Marie Curie
193-
Received message: Steven Hawking
194-
Received message: Isaac Newton
195-
Received message: Niels Bohr
196-
Received message: Michael Faraday
197-
Received message: Galileo Galilei
198-
Received message: Johannes Kepler
199-
Received message: Nikolaus Kopernikus
409+
node receive.js
200410
```
201411
412+
---
413+
414+
You should see the following output.
415+
416+
```console
417+
Received message: Albert Einstein
418+
Received message: Werner Heisenberg
419+
Received message: Marie Curie
420+
Received message: Steven Hawking
421+
Received message: Isaac Newton
422+
Received message: Niels Bohr
423+
Received message: Michael Faraday
424+
Received message: Galileo Galilei
425+
Received message: Johannes Kepler
426+
Received message: Nikolaus Kopernikus
427+
```
428+
202429
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.
203430
204431
:::image type="content" source="./media/service-bus-java-how-to-use-queues/overview-incoming-outgoing-messages.png" alt-text="Incoming and outgoing message count":::
205432
206433
Select the queue on this **Overview** page to navigate to the **Service Bus Queue** page. You see the **incoming** and **outgoing** message count on this page too. You also see other information such as the **current size** of the queue, **maximum size**, **active message count**, and so on.
207434
208435
:::image type="content" source="./media/service-bus-java-how-to-use-queues/queue-details.png" alt-text="Queue details":::
436+
437+
## Troubleshooting
438+
439+
If you receive one of the following errors when running the **passwordless** version of the JavaScript code, make sure you are signed in via the Azure CLI command, `az login` and the [appropriate role](#azure-built-in-roles-for-azure-service-bus) is applied to your Azure user account:
440+
441+
* 'Send' claim(s) are required to perform this operation
442+
* 'Receive' claim(s) are required to perform this operation
443+
444+
## Clean up resources
445+
446+
Navigate to your Service Bus namespace in the Azure portal, and select **Delete** on the Azure portal to delete the namespace and the queue in it.
447+
209448
## Next steps
210449
See the following documentation and samples:
211450

0 commit comments

Comments
 (0)