快速入门:使用 Node.js 和预览版 azure/service-bus 包的服务总线主题与订阅Quickstart: Service Bus topics and subscriptions with Node.js and the preview azure/service-bus package
本教程介绍如何使用 JavaScript 程序中的 @azure/service-bus 包将消息发送到服务总线主题,并从该主题的服务总线订阅接收消息。In this tutorial, you learn how to use the @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.
先决条件Prerequisites
- Azure 订阅。An Azure subscription. 若要完成本教程,需要一个 Azure 帐户。To complete this tutorial, you need an Azure account. 你可以激活 MSDN 订阅者权益或注册试用版订阅。You can activate your MSDN subscriber benefits or sign up for a trial subscription.
- 遵循快速入门:使用 Azure 门户创建一个服务总线主题和多个对该主题的订阅。Follow steps in the Quickstart: Use the Azure portal to create a Service Bus topic and subscriptions to the topic. 记下连接字符串、主题名称和订阅名称。Note down the connection string, topic name, and a subscription name. 本快速入门仅需使用一个订阅。You will use only one subscription for this quickstart.
备注
- 本教程将演练可以使用 Nodejs 复制和运行的示例。This tutorial works with samples that you can copy and run using Nodejs. 有关如何创建 Node.js 应用程序的说明,请参阅创建 Node.js 应用程序并将其部署到 Azure 网站或使用 Windows PowerShell 创建 Node.js 云服务。For instructions on how to create a Node.js application, see Create and deploy a Node.js application to an Azure Website, or Node.js Cloud Service using Windows PowerShell.
使用节点包管理器 (NPM) 安装包Use Node Package Manager (NPM) to install the package
若要安装服务总线的 npm 包,请打开路径中包含 npm
的命令提示符,将目录更改为要包含示例的文件夹,然后运行此命令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.
npm install @azure/service-bus
将消息发送到主题Send messages to a topic
下面的示例代码演示如何将一批消息发送到服务总线主题。The following sample code shows you how to send a batch of messages to a Service Bus topic. 请参阅代码注释以了解详细信息。See code comments for details.
打开你喜好的编辑器,例如 Visual Studio CodeOpen your favorite editor, such as Visual Studio Code
创建一个名为
sendtotopic.js
的文件,并将下面的代码粘贴到其中。Create a file calledsendtotopic.js
and paste the below code into it. 此代码向主题发送一条消息。This code will send a message to your topic.const { ServiceBusClient } = require("@azure/service-bus"); const connectionString = "<SERVICE BUS NAMESPACE CONNECTION STRING>" const topicName = "<TOPIC NAME>"; const messages = [ { body: "Albert Einstein" }, { body: "Werner Heisenberg" }, { body: "Marie Curie" }, { body: "Steven Hawking" }, { body: "Isaac Newton" }, { body: "Niels Bohr" }, { body: "Michael Faraday" }, { body: "Galileo Galilei" }, { body: "Johannes Kepler" }, { body: "Nikolaus Kopernikus" } ]; async function main() { // create a Service Bus client using the connection string to the Service Bus namespace const sbClient = new ServiceBusClient(connectionString); // createSender() can also be used to create a sender for a queue. const sender = sbClient.createSender(topicName); try { // Tries to send all messages in a single batch. // Will fail if the messages cannot fit in a batch. // await sender.sendMessages(messages); // create a batch object let batch = await sender.createMessageBatch(); for (let i = 0; i < messages.length; i++) { // for each message in the arry // try to add the message to the batch if (!batch.tryAddMessage(messages[i])) { // if it fails to add the message to the current batch // send the current batch as it is full await sender.sendMessages(batch); // then, create a new batch batch = await sender.createBatch(); // now, add the message failed to be added to the previous batch to this batch if (!batch.tryAddMessage(messages[i])) { // if it still can't be added to the batch, the message is probably too big to fit in a batch throw new Error("Message too big to fit in a batch"); } } } // Send the last created batch of messages to the topic await sender.sendMessages(batch); console.log(`Sent a batch of messages to the topic: ${topicName}`); // Close the sender await sender.close(); } finally { await sbClient.close(); } } // call the main function main().catch((err) => { console.log("Error occurred: ", err); process.exit(1); });
将
<SERVICE BUS NAMESPACE CONNECTION STRING>
替换为服务总线命名空间的连接字符串。Replace<SERVICE BUS NAMESPACE CONNECTION STRING>
with the connection string to your Service Bus namespace.将
<TOPIC NAME>
替换为主题名称。Replace<TOPIC NAME>
with the name of the topic.然后,在命令提示符中运行该命令以执行此文件。Then run the command in a command prompt to execute this file.
node sendtotopic.js
你会看到以下输出。You should see the following output.
Sent a batch of messages to the topic: mytopic
从订阅接收消息Receive messages from a subscription
打开你喜好的编辑器,例如 Visual Studio CodeOpen your favorite editor, such as Visual Studio Code
创建名为 receivefromsubscription.js 的文件,然后将以下代码粘贴到其中。Create a file called receivefromsubscription.js and paste the following code into it. 请参阅代码注释以了解详细信息。See code comments for details.
const { delay, ServiceBusClient, ServiceBusMessage } = require("@azure/service-bus"); const connectionString = "<SERVICE BUS NAMESPACE CONNECTION STRING>" const topicName = "<TOPIC NAME>"; const subscriptionName = "<SUBSCRIPTION NAME>"; async function main() { // create a Service Bus client using the connection string to the Service Bus namespace const sbClient = new ServiceBusClient(connectionString); // createReceiver() can also be used to create a receiver for a queue. const receiver = sbClient.createReceiver(topicName, subscriptionName); // function to handle messages const myMessageHandler = async (messageReceived) => { console.log(`Received message: ${messageReceived.body}`); }; // function to handle any errors const myErrorHandler = async (error) => { console.log(error); }; // subscribe and specify the message and error handlers receiver.subscribe({ processMessage: myMessageHandler, processError: myErrorHandler }); // Waiting long enough before closing the sender to send messages await delay(5000); await receiver.close(); await sbClient.close(); } // call the main function main().catch((err) => { console.log("Error occurred: ", err); process.exit(1); });
将
<SERVICE BUS NAMESPACE CONNECTION STRING>
替换为命名空间的连接字符串。Replace<SERVICE BUS NAMESPACE CONNECTION STRING>
with the connection string to the namespace.将
<TOPIC NAME>
替换为主题名称。Replace<TOPIC NAME>
with the name of the topic.将
<SUBSCRIPTION NAME>
替换为主题的订阅名称。Replace<SUBSCRIPTION NAME>
with the name of the subscription to the topic.然后,在命令提示符中运行该命令以执行此文件。Then run the command in a command prompt to execute this file.
node receivefromsubscription.js
你会看到以下输出。You should see the following output.
Received message: Albert Einstein Received message: Werner Heisenberg Received message: Marie Curie Received message: Steven Hawking Received message: Isaac Newton Received message: Niels Bohr Received message: Michael Faraday Received message: Galileo Galilei Received message: Johannes Kepler Received message: Nikolaus Kopernikus
在 Azure 门户中,导航到服务总线命名空间,然后选择底部窗格中的主题,以查看主题的“服务总线主题”页面。In the Azure portal, navigate to your Service Bus namespace, and select the topic in the bottom pane to see the Service Bus Topic page for your topic. 在此页上,应会在“消息”图表中看到三条传入消息和三条传出消息。On this page, you should see three incoming and three outgoing messages in the Messages chart.
如果下次仅运行发送应用,那么在“服务总线主题”页上,除 3 条传出消息外,你还会看到 6 条传入消息(3 条新消息)。If you run the only the send app next time, on the Service Bus Topic page, you see six incoming messages (3 new) but three outgoing messages.
在此页上,如果选择一个订阅,则将转到“服务总线订阅”页。On this page, if you select a subscription, you get to the Service Bus Subscription page. 可以在此页上查看活动消息计数、死信消息计数等。You can see the active message count, dead-letter message count, and more on this page. 在此示例中,还有三条活动消息未被接收器接收。In this example, there are three active messages that haven't been received by a receiver yet.
后续步骤Next steps
请参阅以下文档和示例:See the following documentation and samples:
- 适用于 Python 的 Azure 服务总线客户端库Azure Service Bus client library for Python
- 示例。Samples. javascript 文件夹包含 JavaScript 示例,typescript 包含 TypeScript 示例 。The javascript folder has JavaScript samples and the typescript has TypeScript samples.
- azure-servicebus 参考文档azure-servicebus reference documentation