快速入门:如何将服务总线队列与 Node.js 和 azure/service-bus 包配合使用Quickstart: How to use Service Bus queues with Node.js and the azure/service-bus package

本教程介绍如何使用新的 @azure/service-bus 包编写一个 Nodejs 程序,用于向/从服务总线队列发送/接收消息。In this tutorial, you learn how to write a Nodejs program to send messages to and receive messages from a Service Bus queue using the new @azure/service-bus package. 此包使用速度更快的 AMQP 1.0 协议,而旧版 azure-sb 包使用的是服务总线 REST 运行时 APIThis package uses the faster AMQP 1.0 protocol whereas the older azure-sb package used Service Bus REST run-time APIs. 示例是使用 JavaScript 编写的。The samples are written in JavaScript.

先决条件Prerequisites

备注

使用节点包管理器 (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

若要与服务总线队列交互,首先需要实例化 ServiceBusClient 类,并使用它来实例化 QueueClient 类。Interacting with a Service Bus queue starts with instantiating the ServiceBusClient class and using it to instantiate the QueueClient class. 安装队列客户端后,可以创建发送方,并在其上使用 sendsendBatch 方法发送消息。Once you have the queue client, you can create a sender and use either send or sendBatch method on it to send messages.

  1. 打开你喜好的编辑器,例如 Visual Studio CodeOpen your favorite editor, such as Visual Studio Code

  2. 创建一个名为 send.js 的文件,并将下面的代码粘贴到其中。Create a file called send.js and paste the below code into it. 此代码会将 10 条消息发送到队列。This code will send 10 messages to your queue.

    const { ServiceBusClient } = require("@azure/service-bus"); 
    
    // Define connection string and related Service Bus entity names here
    const connectionString = "";
    const queueName = ""; 
    
    async function main(){
      const sbClient = ServiceBusClient.createFromConnectionString(connectionString); 
      const queueClient = sbClient.createQueueClient(queueName);
      const sender = queueClient.createSender();
    
      try {
        for (let i = 0; i < 10; i++) {
          const message= {
            body: `Hello world! ${i}`,
            label: `test`,
            userProperties: {
                myCustomPropertyName: `my custom property value ${i}`
           }
          };
          console.log(`Sending message: ${message.body}`);
          await sender.send(message);
        }
    
        await queueClient.close();
      } finally {
        await sbClient.close();
      }
    }
    
    main().catch((err) => {
      console.log("Error occurred: ", err);
    });
    
  3. 输入以上代码中显示的连接字符串和队列名称。Enter the connection string and name of your queue in the above code.

  4. 然后在命令提示符下运行命令 node send.js 以执行此文件。Then run the command node send.js in a command prompt to execute this file.

祝贺!Congratulations! 你已将消息发送到服务总线队列。You just sent messages to a Service Bus queue.

消息中包含 labelmessageId 等标准属性,在发送时可以设置这些属性。Messages have some standard properties like label and messageId that you can set when sending. 若要设置任何自定义属性,请使用 userProperties(一个可以保存自定义数据的键值对的 JSON 对象)。If you want to set any custom properties, use the userProperties, which is a json object that can hold key-value pairs of your custom data.

服务总线队列在标准层中支持的最大消息大小为 256 KB,在高级层中则为 1 MB。Service Bus queues support a maximum message size of 256 KB in the Standard tier and 1 MB in the Premium tier. 一个队列中包含的消息数量不受限制,但消息的总大小受限制。There's no limit on the number of messages held in a queue but there's a cap on the total size of the messages held by a queue. 此队列大小在创建时定义,上限为 5 GB。This queue size is defined at creation time, with an upper limit of 5 GB. 有关配额的详细信息,请参阅 服务总线配额For more information about quotas, see Service Bus quotas.

从队列接收消息Receive messages from a queue

若要与服务总线队列交互,首先需要实例化 ServiceBusClient 类,并使用它来实例化 QueueClient 类。Interacting with a Service Bus queue starts with instantiating the ServiceBusClient class and using it to instantiate the QueueClient class. 安装队列客户端后,可以创建接收方,并在其上使用 receiveMessagesregisterMessageHandler 方法来接收消息。Once you have the queue client, you can create a receiver and use either receiveMessages or registerMessageHandler method on it to receive messages.

  1. 打开你喜好的编辑器,例如 Visual Studio CodeOpen your favorite editor, such as Visual Studio Code

  2. 创建一个名为 recieve.js 的文件,并将下面的代码粘贴到其中。Create a file called recieve.js and paste the below code into it. 此代码尝试从队列接收 10 条消息。This code will attempt to receive 10 messages from your queue. 收到的实际消息计数取决于队列中的消息数以及网络延迟。The actual count you receive depends on the number of messages in the queue and network latency.

    const { ServiceBusClient, ReceiveMode } = require("@azure/service-bus"); 
    
    // Define connection string and related Service Bus entity names here
    const connectionString = "";
    const queueName = ""; 
    
    async function main(){
      const sbClient = ServiceBusClient.createFromConnectionString(connectionString); 
      const queueClient = sbClient.createQueueClient(queueName);
      const receiver = queueClient.createReceiver(ReceiveMode.receiveAndDelete);
      try {
        const messages = await receiver.receiveMessages(10)
        console.log("Received messages:");
        console.log(messages.map(message => message.body));
    
        await queueClient.close();
      } finally {
        await sbClient.close();
      }
    }
    
    main().catch((err) => {
      console.log("Error occurred: ", err);
    });
    
  3. 输入以上代码中显示的连接字符串和队列名称。Enter the connection string and name of your queue in the above code.

  4. 然后在命令提示符下运行命令 node receiveMessages.js 以执行此文件。Then run the command node receiveMessages.js in a command prompt to execute this file.

祝贺!Congratulations! 你已从服务总线队列收到了消息。You just received messages from a Service Bus queue.

createReceiver 方法采用 ReceiveMode(值为 ReceiveAndDeletePeekLock 的枚举)。The createReceiver method takes in a ReceiveMode which is an enum with values ReceiveAndDelete and PeekLock. 如果你使用 PeekLock 模式,请记得对消息使用 complete()abandon()defer()deadletter()最终处理消息Remember to settle your messages if you use the PeekLock mode by using any of complete(), abandon(), defer(), or deadletter() methods on the message.

备注

可以使用服务总线资源管理器管理服务总线资源。You can manage Service Bus resources with Service Bus Explorer. 服务总线资源管理器允许用户连接到服务总线命名空间并以一种简单的方式管理消息传送实体。The Service Bus Explorer allows users to connect to a Service Bus namespace and administer messaging entities in an easy manner. 该工具提供高级功能,如导入/导出功能或用于对主题、队列、订阅、中继服务、通知中心和事件中心进行测试的功能。The tool provides advanced features like import/export functionality or the ability to test topic, queues, subscriptions, relay services, notification hubs and events hubs.

后续步骤Next steps

有关详细信息,请参阅以下资源。To learn more, see the following resources.