Skip to content

Commit 170973a

Browse files
Merge pull request #218997 from diberry/service-bus-js-publish-and-subscript
Service Bus Queue - JS Quickstart - pub/sub
2 parents 97f76e3 + 98e8065 commit 170973a

File tree

2 files changed

+256
-26
lines changed

2 files changed

+256
-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: 254 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,178 @@ 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.
3559

36-
```bash
37-
npm install @azure/service-bus
38-
```
60+
[!INCLUDE [service-bus-create-namespace-portal](./includes/service-bus-create-namespace-portal.md)]
61+
62+
[!INCLUDE [service-bus-create-topic-subscription-portal](./includes/service-bus-create-topic-subscription-portal.md)]
63+
64+
[!INCLUDE [service-bus-passwordless-template-tabbed](../../includes/passwordless/service-bus/service-bus-passwordless-template-tabbed.md)]
65+
66+
## Use Node Package Manager (NPM) to install the package
67+
68+
### [Passwordless](#tab/passwordless)
69+
70+
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.
71+
72+
1. Install the following packages:
73+
74+
```bash
75+
npm install @azure/service-bus @azure/identity
76+
```
77+
78+
### [Connection string](#tab/connection-string)
79+
80+
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.
81+
82+
1. Install the following package:
83+
84+
```bash
85+
npm install @azure/service-bus
86+
```
87+
88+
---
3989

4090
## Send messages to a topic
4191
The following sample code shows you how to send a batch of messages to a Service Bus topic. See code comments for details.
4292

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+
2. Create a file called `sendtotopic.js` and paste the below code into it. This code will send a message to your topic.
99+
100+
```javascript
101+
const { ServiceBusClient } = require("@azure/service-bus");
102+
const { DefaultAzureCredential } = require("@azure/identity");
103+
104+
// Replace `<SERVICE-BUS-NAMESPACE>` with your namespace
105+
const fullyQualifiedNamespace = "<SERVICE-BUS-NAMESPACE>.servicebus.windows.net";
106+
107+
// Passwordless credential
108+
const credential = new DefaultAzureCredential();
109+
110+
const topicName = "<TOPIC NAME>";
111+
112+
const messages = [
113+
{ body: "Albert Einstein" },
114+
{ body: "Werner Heisenberg" },
115+
{ body: "Marie Curie" },
116+
{ body: "Steven Hawking" },
117+
{ body: "Isaac Newton" },
118+
{ body: "Niels Bohr" },
119+
{ body: "Michael Faraday" },
120+
{ body: "Galileo Galilei" },
121+
{ body: "Johannes Kepler" },
122+
{ body: "Nikolaus Kopernikus" }
123+
];
124+
125+
async function main() {
126+
// create a Service Bus client using the passwordless authentication to the Service Bus namespace
127+
const sbClient = new ServiceBusClient(fullyQualifiedNamespace, credential);
128+
129+
// createSender() can also be used to create a sender for a queue.
130+
const sender = sbClient.createSender(topicName);
131+
132+
try {
133+
// Tries to send all messages in a single batch.
134+
// Will fail if the messages cannot fit in a batch.
135+
// await sender.sendMessages(messages);
136+
137+
// create a batch object
138+
let batch = await sender.createMessageBatch();
139+
for (let i = 0; i < messages.length; i++) {
140+
// for each message in the arry
141+
142+
// try to add the message to the batch
143+
if (!batch.tryAddMessage(messages[i])) {
144+
// if it fails to add the message to the current batch
145+
// send the current batch as it is full
146+
await sender.sendMessages(batch);
147+
148+
// then, create a new batch
149+
batch = await sender.createMessageBatch();
150+
151+
// now, add the message failed to be added to the previous batch to this batch
152+
if (!batch.tryAddMessage(messages[i])) {
153+
// if it still can't be added to the batch, the message is probably too big to fit in a batch
154+
throw new Error("Message too big to fit in a batch");
155+
}
156+
}
157+
}
158+
159+
// Send the last created batch of messages to the topic
160+
await sender.sendMessages(batch);
161+
162+
console.log(`Sent a batch of messages to the topic: ${topicName}`);
163+
164+
// Close the sender
165+
await sender.close();
166+
} finally {
167+
await sbClient.close();
168+
}
169+
}
170+
171+
// call the main function
172+
main().catch((err) => {
173+
console.log("Error occurred: ", err);
174+
process.exit(1);
175+
});
176+
```
177+
3. Replace `<SERVICE BUS NAMESPACE CONNECTION STRING>` with the connection string to your Service Bus namespace.
178+
1. Replace `<TOPIC NAME>` with the name of the topic.
179+
1. Then run the command in a command prompt to execute this file.
180+
181+
```console
182+
node sendtotopic.js
183+
```
184+
1. You should see the following output.
185+
186+
```console
187+
Sent a batch of messages to the topic: mytopic
188+
```
189+
190+
### [Connection string](#tab/connection-string)
191+
43192
1. Open your favorite editor, such as [Visual Studio Code](https://code.visualstudio.com/)
44193
2. Create a file called `sendtotopic.js` and paste the below code into it. This code will send a message to your topic.
45194
@@ -127,7 +276,77 @@ The following sample code shows you how to send a batch of messages to a Service
127276
Sent a batch of messages to the topic: mytopic
128277
```
129278
279+
---
280+
130281
## Receive messages from a subscription
282+
283+
### [Passwordless](#tab/passwordless)
284+
285+
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.
286+
287+
1. Open your favorite editor, such as [Visual Studio Code](https://code.visualstudio.com/)
288+
2. Create a file called **receivefromsubscription.js** and paste the following code into it. See code comments for details.
289+
290+
```javascript
291+
const { delay, ServiceBusClient, ServiceBusMessage } = require("@azure/service-bus");
292+
const { DefaultAzureCredential } = require("@azure/identity");
293+
294+
// Replace `<SERVICE-BUS-NAMESPACE>` with your namespace
295+
const fullyQualifiedNamespace = "<SERVICE-BUS-NAMESPACE>.servicebus.windows.net";
296+
297+
// Passwordless credential
298+
const credential = new DefaultAzureCredential();
299+
300+
const topicName = "<TOPIC NAME>";
301+
const subscriptionName = "<SUBSCRIPTION NAME>";
302+
303+
async function main() {
304+
// create a Service Bus client using the passwordless authentication to the Service Bus namespace
305+
const sbClient = new ServiceBusClient(fullyQualifiedNamespace, credential);
306+
307+
// createReceiver() can also be used to create a receiver for a queue.
308+
const receiver = sbClient.createReceiver(topicName, subscriptionName);
309+
310+
// function to handle messages
311+
const myMessageHandler = async (messageReceived) => {
312+
console.log(`Received message: ${messageReceived.body}`);
313+
};
314+
315+
// function to handle any errors
316+
const myErrorHandler = async (error) => {
317+
console.log(error);
318+
};
319+
320+
// subscribe and specify the message and error handlers
321+
receiver.subscribe({
322+
processMessage: myMessageHandler,
323+
processError: myErrorHandler
324+
});
325+
326+
// Waiting long enough before closing the sender to send messages
327+
await delay(5000);
328+
329+
await receiver.close();
330+
await sbClient.close();
331+
}
332+
333+
// call the main function
334+
main().catch((err) => {
335+
console.log("Error occurred: ", err);
336+
process.exit(1);
337+
});
338+
```
339+
3. Replace `<SERVICE BUS NAMESPACE CONNECTION STRING>` with the connection string to the namespace.
340+
4. Replace `<TOPIC NAME>` with the name of the topic.
341+
5. Replace `<SUBSCRIPTION NAME>` with the name of the subscription to the topic.
342+
6. Then run the command in a command prompt to execute this file.
343+
344+
```console
345+
node receivefromsubscription.js
346+
```
347+
348+
### [Connection string](#tab/connection-string)
349+
131350
1. Open your favorite editor, such as [Visual Studio Code](https://code.visualstudio.com/)
132351
2. Create a file called **receivefromsubscription.js** and paste the following code into it. See code comments for details.
133352
@@ -175,27 +394,30 @@ The following sample code shows you how to send a batch of messages to a Service
175394
});
176395
```
177396
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.
397+
4. Replace `<TOPIC NAME>` with the name of the topic.
398+
5. Replace `<SUBSCRIPTION NAME>` with the name of the subscription to the topic.
399+
6. Then run the command in a command prompt to execute this file.
181400
182401
```console
183402
node receivefromsubscription.js
184403
```
185-
1. You should see the following output.
186404
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-
```
405+
---
406+
407+
You should see the following output.
408+
409+
```console
410+
Received message: Albert Einstein
411+
Received message: Werner Heisenberg
412+
Received message: Marie Curie
413+
Received message: Steven Hawking
414+
Received message: Isaac Newton
415+
Received message: Niels Bohr
416+
Received message: Michael Faraday
417+
Received message: Galileo Galilei
418+
Received message: Johannes Kepler
419+
Received message: Nikolaus Kopernikus
420+
```
199421
200422
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.
201423
@@ -209,6 +431,14 @@ On this page, if you select a subscription in the bottom pane, you get to the **
209431
210432
:::image type="content" source="./media/service-bus-nodejs-how-to-use-topics-subscriptions/active-message-count.png" alt-text="Active message count":::
211433
434+
## Troubleshooting
435+
436+
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.
437+
438+
## Clean up resources
439+
440+
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.
441+
212442
## Next steps
213443
See the following documentation and samples:
214444

0 commit comments

Comments
 (0)