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

本教程介绍如何使用新的 @azure/service-bus 包编写一个 Node.js 程序,用于将消息发送到服务总线主题,并从服务总线订阅接收消息。In this tutorial, you learn how to write a Node.js program to send messages to a Service Bus topic and receive messages from a Service Bus subscription 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 topic

若要与服务总线主题交互,首先需要实例化 ServiceBusClient 类,并使用它来实例化 TopicClient 类。Interacting with a Service Bus topic starts with instantiating the ServiceBusClient class and using it to instantiate the TopicClient class. 安装主题客户端后,可以创建发送方,并在其上使用 sendsendBatch 方法发送消息。Once you have the topic 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 topic.

    const { ServiceBusClient } = require("@azure/service-bus"); 
    
    // Define connection string and related Service Bus entity names here
    const connectionString = "";
    const topicName = ""; 
    
    async function main(){
      const sbClient = ServiceBusClient.createFromConnectionString(connectionString); 
      const topicClient = sbClient.createTopicClient(topicName);
      const sender = topicClient.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 topicClient.close();
          } finally {
            await sbClient.close();
          }
    }
    
    main().catch((err) => {
      console.log("Error occurred: ", err);
    });
    
  3. 输入以上代码中显示的连接字符串和主题名称。Enter the connection string and name of your topic 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 topics 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 topic, but there's a limit on the total size of the messages held by a topic. 此主题大小是在创建时定义的,上限为 5 GB。This topic 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 subscription

若要与服务总线订阅交互,首先需要实例化 ServiceBusClient 类,并使用它来实例化 SubscriptionClient 类。Interacting with a Service Bus subscription starts with instantiating the ServiceBusClient class and using it to instantiate the SubscriptionClient class. 安装订阅客户端后,可以创建接收方,并在其上使用 receiveMessagesregisterMessageHandler 方法来接收消息。Once you have the subscription 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. 创建一个名为 receive.js 的文件,并将下面的代码粘贴到其中。Create a file called receive.js and paste the below code into it. 此代码尝试从订阅接收 10 条消息。This code will attempt to receive 10 messages from your subscription. 收到的实际消息计数取决于订阅中的消息数以及网络延迟。The actual count you receive depends on the number of messages in the subscription and network latency.

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

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

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

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.

订阅筛选器和操作Subscription filters and actions

服务总线支持对订阅使用筛选器和操作,这样,你就可以根据订阅筛选传入的消息并编辑其属性。Service Bus supports filters and actions on subscriptions, which allows you to filter the incoming messages to a subscription and to edit their properties.

获取 SubscriptionClient 的实例后,可对其使用以下方法,以在订阅中获取、添加和删除用于控制筛选器与操作的规则。Once you have an instance of a SubscriptionClient you can use the below methods on it to get, add and remove rules on the subscription to control the filters and actions.

  • getRulesgetRules
  • addRuleaddRule
  • removeRuleremoveRule

在每个订阅中,有一个默认规则使用 true 筛选器来允许所有传入消息。Every subscription has a default rule that uses the true filter to allow all incoming messages. 添加新规则时,请记得删除默认筛选器,使新规则中的筛选器正常工作。When you add a new rule, remember to remove the default filter in order for the filter in your new rule to work. 如果订阅中没有规则,则它不会收到任何消息。If a subscription has no rules, then it will receive no messages.

备注

可以使用服务总线资源管理器管理服务总线资源。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.