Skip to content

Commit 1803356

Browse files
committed
Service Bus Queue - JS Quickstart - pub/sub
1 parent 1b14adc commit 1803356

File tree

2 files changed

+249
-26
lines changed

2 files changed

+249
-26
lines changed

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -126,7 +126,7 @@ You must have signed in with the Azure CLI's `az login` in order for your local
126126
];
127127
128128
async function main() {
129-
// create a Service Bus client using the connection string to the Service Bus namespace
129+
// create a Service Bus client using the passwordless authentication to the Service Bus namespace
130130
const sbClient = new ServiceBusClient(fullyQualifiedNamespace, credential);
131131
132132
// createSender() can also be used to create a sender for a topic.
@@ -308,7 +308,7 @@ You must have signed in with the Azure CLI's `az login` in order for your local
308308
const queueName = "<QUEUE NAME>"
309309
310310
async function main() {
311-
// create a Service Bus client using the connection string to the Service Bus namespace
311+
// create a Service Bus client using the passwordless authentication to the Service Bus namespace
312312
const sbClient = new ServiceBusClient(fullyQualifiedNamespace, credential);
313313
314314
// createReceiver() can also be used to create a receiver for a subscription.

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

Lines changed: 247 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ title: Get started with Azure Service Bus topics (JavaScript)
33
description: This tutorial shows you how to send messages to Azure Service Bus topics and receive messages from topics' subscriptions using the JavaScript programming language.
44
author: spelluru
55
ms.author: spelluru
6-
ms.date: 02/16/2022
6+
ms.date: 11/18/2022
77
ms.topic: quickstart
88
ms.devlang: javascript
99
ms.custom: devx-track-js, mode-api
@@ -17,29 +17,171 @@ ms.custom: devx-track-js, mode-api
1717
> * [JavaScript](service-bus-nodejs-how-to-use-topics-subscriptions.md)
1818
> * [Python](service-bus-python-how-to-use-topics-subscriptions.md)
1919
20+
In this tutorial, you complete the following steps:
2021

21-
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 a Service Bus topic and receive messages from a Service Bus subscription to that topic.
22+
1. Create a Service Bus namespace, using the Azure portal.
23+
2. Create a Service Bus topic, using the Azure portal.
24+
3. Create a Service Bus subscription to that topic, using the Azure portal.
25+
4. Write a JavaScript application to use the [@azure/service-bus](https://www.npmjs.com/package/@azure/service-bus) package to:
26+
* Send a set of messages to the topic.
27+
* Receive those messages from the subscription.
2228

2329
> [!NOTE]
2430
> This quick start provides step-by-step instructions for a simple scenario of sending a batch of messages to a Service Bus topic and receiving those messages from a subscription of the topic. 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).
2531
2632
## Prerequisites
2733
- 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).
28-
- Follow steps in the [Quickstart: Use the Azure portal to create a Service Bus topic and subscriptions to the topic](service-bus-quickstart-topics-subscriptions-portal.md). Note down the connection string, topic name, and a subscription name. You will use only one subscription for this quickstart.
34+
- [Node.js LTS](https://nodejs.org/en/download/)
35+
- Follow steps in the [Quickstart: Use the Azure portal to create a Service Bus topic and subscriptions to the topic](service-bus-quickstart-topics-subscriptions-portal.md). You will use only one subscription for this quickstart.
36+
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 role to your resource.
44+
* Run the code in the same terminal or command prompt.
45+
* Note down your **topic** name and **subscription** 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 **topic** name you created
52+
* Service Bus namespace **subscription**
53+
54+
---
2955

3056
> [!NOTE]
3157
> - 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).
3258
33-
### Use Node Package Manager (NPM) to install the package
34-
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.
59+
## Use Node Package Manager (NPM) to install the package
3560

36-
```bash
37-
npm install @azure/service-bus
38-
```
61+
### [Passwordless](#tab/passwordless)
62+
63+
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.
64+
65+
1. Install the following packages:
66+
67+
```bash
68+
npm install @azure/service-bus @azure/identity
69+
```
70+
71+
### [Connection string](#tab/connection-string)
72+
73+
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.
74+
75+
1. Install the following package:
76+
77+
```bash
78+
npm install @azure/service-bus
79+
```
80+
81+
---
3982

4083
## Send messages to a topic
4184
The following sample code shows you how to send a batch of messages to a Service Bus topic. See code comments for details.
4285

86+
### [Passwordless](#tab/passwordless)
87+
88+
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.
89+
90+
1. Open your favorite editor, such as [Visual Studio Code](https://code.visualstudio.com/)
91+
2. Create a file called `sendtotopic.js` and paste the below code into it. This code will send a message to your topic.
92+
93+
```javascript
94+
const { ServiceBusClient } = require("@azure/service-bus");
95+
const { DefaultAzureCredential } = require("@azure/identity");
96+
97+
// Replace `<SERVICE-BUS-NAMESPACE>` with your namespace
98+
const fullyQualifiedNamespace = "<SERVICE-BUS-NAMESPACE>.servicebus.windows.net";
99+
100+
// Passwordless credential
101+
const credential = new DefaultAzureCredential();
102+
103+
const topicName = "<TOPIC NAME>";
104+
105+
const messages = [
106+
{ body: "Albert Einstein" },
107+
{ body: "Werner Heisenberg" },
108+
{ body: "Marie Curie" },
109+
{ body: "Steven Hawking" },
110+
{ body: "Isaac Newton" },
111+
{ body: "Niels Bohr" },
112+
{ body: "Michael Faraday" },
113+
{ body: "Galileo Galilei" },
114+
{ body: "Johannes Kepler" },
115+
{ body: "Nikolaus Kopernikus" }
116+
];
117+
118+
async function main() {
119+
// create a Service Bus client using the passwordless authentication to the Service Bus namespace
120+
const sbClient = new ServiceBusClient(fullyQualifiedNamespace, credential);
121+
122+
// createSender() can also be used to create a sender for a queue.
123+
const sender = sbClient.createSender(topicName);
124+
125+
try {
126+
// Tries to send all messages in a single batch.
127+
// Will fail if the messages cannot fit in a batch.
128+
// await sender.sendMessages(messages);
129+
130+
// create a batch object
131+
let batch = await sender.createMessageBatch();
132+
for (let i = 0; i < messages.length; i++) {
133+
// for each message in the arry
134+
135+
// try to add the message to the batch
136+
if (!batch.tryAddMessage(messages[i])) {
137+
// if it fails to add the message to the current batch
138+
// send the current batch as it is full
139+
await sender.sendMessages(batch);
140+
141+
// then, create a new batch
142+
batch = await sender.createMessageBatch();
143+
144+
// now, add the message failed to be added to the previous batch to this batch
145+
if (!batch.tryAddMessage(messages[i])) {
146+
// if it still can't be added to the batch, the message is probably too big to fit in a batch
147+
throw new Error("Message too big to fit in a batch");
148+
}
149+
}
150+
}
151+
152+
// Send the last created batch of messages to the topic
153+
await sender.sendMessages(batch);
154+
155+
console.log(`Sent a batch of messages to the topic: ${topicName}`);
156+
157+
// Close the sender
158+
await sender.close();
159+
} finally {
160+
await sbClient.close();
161+
}
162+
}
163+
164+
// call the main function
165+
main().catch((err) => {
166+
console.log("Error occurred: ", err);
167+
process.exit(1);
168+
});
169+
```
170+
3. Replace `<SERVICE BUS NAMESPACE CONNECTION STRING>` with the connection string to your Service Bus namespace.
171+
1. Replace `<TOPIC NAME>` with the name of the topic.
172+
1. Then run the command in a command prompt to execute this file.
173+
174+
```console
175+
node sendtotopic.js
176+
```
177+
1. You should see the following output.
178+
179+
```console
180+
Sent a batch of messages to the topic: mytopic
181+
```
182+
183+
### [Connection string](#tab/connection-string)
184+
43185
1. Open your favorite editor, such as [Visual Studio Code](https://code.visualstudio.com/)
44186
2. Create a file called `sendtotopic.js` and paste the below code into it. This code will send a message to your topic.
45187
@@ -127,7 +269,77 @@ The following sample code shows you how to send a batch of messages to a Service
127269
Sent a batch of messages to the topic: mytopic
128270
```
129271
272+
---
273+
130274
## Receive messages from a subscription
275+
276+
### [Passwordless](#tab/passwordless)
277+
278+
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.
279+
280+
1. Open your favorite editor, such as [Visual Studio Code](https://code.visualstudio.com/)
281+
2. Create a file called **receivefromsubscription.js** and paste the following code into it. See code comments for details.
282+
283+
```javascript
284+
const { delay, ServiceBusClient, ServiceBusMessage } = require("@azure/service-bus");
285+
const { DefaultAzureCredential } = require("@azure/identity");
286+
287+
// Replace `<SERVICE-BUS-NAMESPACE>` with your namespace
288+
const fullyQualifiedNamespace = "<SERVICE-BUS-NAMESPACE>.servicebus.windows.net";
289+
290+
// Passwordless credential
291+
const credential = new DefaultAzureCredential();
292+
293+
const topicName = "<TOPIC NAME>";
294+
const subscriptionName = "<SUBSCRIPTION NAME>";
295+
296+
async function main() {
297+
// create a Service Bus client using the passwordless authentication to the Service Bus namespace
298+
const sbClient = new ServiceBusClient(fullyQualifiedNamespace, credential);
299+
300+
// createReceiver() can also be used to create a receiver for a queue.
301+
const receiver = sbClient.createReceiver(topicName, subscriptionName);
302+
303+
// function to handle messages
304+
const myMessageHandler = async (messageReceived) => {
305+
console.log(`Received message: ${messageReceived.body}`);
306+
};
307+
308+
// function to handle any errors
309+
const myErrorHandler = async (error) => {
310+
console.log(error);
311+
};
312+
313+
// subscribe and specify the message and error handlers
314+
receiver.subscribe({
315+
processMessage: myMessageHandler,
316+
processError: myErrorHandler
317+
});
318+
319+
// Waiting long enough before closing the sender to send messages
320+
await delay(5000);
321+
322+
await receiver.close();
323+
await sbClient.close();
324+
}
325+
326+
// call the main function
327+
main().catch((err) => {
328+
console.log("Error occurred: ", err);
329+
process.exit(1);
330+
});
331+
```
332+
3. Replace `<SERVICE BUS NAMESPACE CONNECTION STRING>` with the connection string to the namespace.
333+
4. Replace `<TOPIC NAME>` with the name of the topic.
334+
5. Replace `<SUBSCRIPTION NAME>` with the name of the subscription to the topic.
335+
6. Then run the command in a command prompt to execute this file.
336+
337+
```console
338+
node receivefromsubscription.js
339+
```
340+
341+
### [Connection string](#tab/connection-string)
342+
131343
1. Open your favorite editor, such as [Visual Studio Code](https://code.visualstudio.com/)
132344
2. Create a file called **receivefromsubscription.js** and paste the following code into it. See code comments for details.
133345
@@ -175,27 +387,30 @@ The following sample code shows you how to send a batch of messages to a Service
175387
});
176388
```
177389
3. Replace `<SERVICE BUS NAMESPACE CONNECTION STRING>` with the connection string to the namespace.
178-
1. Replace `<TOPIC NAME>` with the name of the topic.
179-
1. Replace `<SUBSCRIPTION NAME>` with the name of the subscription to the topic.
180-
1. Then run the command in a command prompt to execute this file.
390+
4. Replace `<TOPIC NAME>` with the name of the topic.
391+
5. Replace `<SUBSCRIPTION NAME>` with the name of the subscription to the topic.
392+
6. Then run the command in a command prompt to execute this file.
181393
182394
```console
183395
node receivefromsubscription.js
184396
```
185-
1. You should see the following output.
186397
187-
```console
188-
Received message: Albert Einstein
189-
Received message: Werner Heisenberg
190-
Received message: Marie Curie
191-
Received message: Steven Hawking
192-
Received message: Isaac Newton
193-
Received message: Niels Bohr
194-
Received message: Michael Faraday
195-
Received message: Galileo Galilei
196-
Received message: Johannes Kepler
197-
Received message: Nikolaus Kopernikus
198-
```
398+
---
399+
400+
You should see the following output.
401+
402+
```console
403+
Received message: Albert Einstein
404+
Received message: Werner Heisenberg
405+
Received message: Marie Curie
406+
Received message: Steven Hawking
407+
Received message: Isaac Newton
408+
Received message: Niels Bohr
409+
Received message: Michael Faraday
410+
Received message: Galileo Galilei
411+
Received message: Johannes Kepler
412+
Received message: Nikolaus Kopernikus
413+
```
199414
200415
In the Azure portal, navigate to your Service Bus namespace, switch to **Topics** in the bottom pane, and select your topic to see the **Service Bus Topic** page for your topic. On this page, you should see 10 incoming and 10 outgoing messages in the **Messages** chart.
201416
@@ -209,6 +424,14 @@ On this page, if you select a subscription in the bottom pane, you get to the **
209424
210425
:::image type="content" source="./media/service-bus-nodejs-how-to-use-topics-subscriptions/active-message-count.png" alt-text="Active message count":::
211426
427+
## Troubleshooting
428+
429+
If you receive an error when running the **passwordless** version of the JavaScript code about required claims, 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.
430+
431+
## Clean up resources
432+
433+
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.
434+
212435
## Next steps
213436
See the following documentation and samples:
214437

0 commit comments

Comments
 (0)