向 Azure 服务总线队列发送消息并从中接收消息 (JavaScript)Send messages to and receive messages from Azure Service Bus queues (JavaScript)
本教程介绍如何使用 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 and receive messages from a Service Bus queue.
先决条件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 门户创建服务总线队列一文来创建队列。If you don't have a queue to work with, follow steps in the Use Azure portal to create a Service Bus queue article to create a queue. 记下服务总线命名空间的连接字符串以及创建的队列的名称 。Note down the connection string for your Service Bus namespace and the name of the queue you created.
备注
- 本教程将演练可以使用 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 queue
以下示例代码演示如何向队列发送消息。The following sample code shows you how to send a message to a queue.
打开偏好的编辑器,例如 Visual Studio Code。Open your favorite editor, such as Visual Studio Code.
创建一个名为
send.js
的文件,并将下面的代码粘贴到其中。Create a file calledsend.js
and paste the below code into it. 此代码将向队列发送一条消息。This code will send a message to your queue. 消息具有标签(科学家)和正文(爱因斯坦)。The message has a label (Scientist) and body (Einstein).const { ServiceBusClient } = require("@azure/service-bus"); // connection string to your Service Bus namespace const connectionString = "<CONNECTION STRING TO SERVICE BUS NAMESPACE>" // name of the queue const queueName = "<QUEUE 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 topic. const sender = sbClient.createSender(queueName); 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 queue await sender.sendMessages(batch); console.log(`Sent a batch of messages to the queue: ${queueName}`); // 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); });
将
<CONNECTION STRING TO SERVICE BUS NAMESPACE>
替换为服务总线命名空间的连接字符串。Replace<CONNECTION STRING TO SERVICE BUS NAMESPACE>
with the connection string to your Service Bus namespace.将
<QUEUE NAME>
替换为该队列的名称。Replace<QUEUE NAME>
with the name of the queue.然后,在命令提示符中运行该命令以执行此文件。Then run the command in a command prompt to execute this file.
node send.js
你会看到以下输出。You should see the following output.
Sent a batch of messages to the queue: myqueue
从队列接收消息Receive messages from a queue
打开你喜好的编辑器,例如 Visual Studio CodeOpen your favorite editor, such as Visual Studio Code
创建名为
receive.js
的文件,然后将以下代码粘贴到其中。Create a file calledreceive.js
and paste the following code into it.const { delay, ServiceBusClient, ServiceBusMessage } = require("@azure/service-bus"); // connection string to your Service Bus namespace const connectionString = "<CONNECTION STRING TO SERVICE BUS NAMESPACE>" // name of the queue const queueName = "<QUEUE 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 subscription. const receiver = sbClient.createReceiver(queueName); // 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); });
将
<CONNECTION STRING TO SERVICE BUS NAMESPACE>
替换为服务总线命名空间的连接字符串。Replace<CONNECTION STRING TO SERVICE BUS NAMESPACE>
with the connection string to your Service Bus namespace.将
<QUEUE NAME>
替换为该队列的名称。Replace<QUEUE NAME>
with the name of the queue.然后,在命令提示符中运行命令以执行此文件。Then, run the command in a command prompt to execute this file.
node receive.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 门户中的服务总线命名空间的“概述”页上,可看到传入和传出消息计数 。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.
在此“概述”页上选择队列,导航到“服务总线队列”页面 。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.
后续步骤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