向 Azure 服务总线队列发送消息并从中接收消息 (JavaScript)

本教程介绍如何使用 JavaScript 程序中的 @azure/service-bus 包向服务总线队列发送消息并从中接收消息。

注意

本快速入门分步介绍了一个简单方案,也就是将消息发送到服务总线队列并接收这些消息。 可在 GitHub 上的 Azure SDK for JavaScript 存储库中找到预生成的 Azure 服务总线 JavaScript 和 TypeScript 示例。

先决条件

注意

使用节点包管理器 (NPM) 安装包

若要安装服务总线的 npm 包,请打开路径中包含 npm 的命令提示符,将目录更改为要包含示例的文件夹,然后运行此命令

npm install @azure/service-bus

向队列发送消息

以下示例代码演示如何向队列发送消息。

  1. 打开偏好的编辑器,例如 Visual Studio Code

  2. 创建一个名为 send.js 的文件,并将下面的代码粘贴到其中。 此代码将科学家的名称作为消息发送到队列。

    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 array			
    
                // 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.createMessageBatch();
    
                    // 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);
     });
    
  3. <CONNECTION STRING TO SERVICE BUS NAMESPACE> 替换为服务总线命名空间的连接字符串。

  4. <QUEUE NAME> 替换为该队列的名称。

  5. 然后,在命令提示符中运行该命令以执行此文件。

    node send.js 
    
  6. 你会看到以下输出。

    Sent a batch of messages to the queue: myqueue
    

从队列接收消息

  1. 打开你喜好的编辑器,例如 Visual Studio Code

  2. 创建名为 receive.js 的文件,然后将以下代码粘贴到其中。

    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(20000);
    
        await receiver.close();	
        await sbClient.close();
    }    
    // call the main function
    main().catch((err) => {
        console.log("Error occurred: ", err);
        process.exit(1);
     });
    
  3. <CONNECTION STRING TO SERVICE BUS NAMESPACE> 替换为服务总线命名空间的连接字符串。

  4. <QUEUE NAME> 替换为该队列的名称。

  5. 然后,在命令提示符中运行命令以执行此文件。

    node receive.js
    
  6. 你会看到以下输出。

    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 门户中的服务总线命名空间的“概述”页上,可看到传入和传出消息计数 。 可能需要等待一分钟左右,然后刷新页面才会看到最新值。

Incoming and outgoing message count

在此“概述”页上选择队列,导航到“服务总线队列”页面 。 还可在此页上看到传入和传出消息计数 。 还可看到其他信息,如队列的当前大小、最大大小和活动消息计数等 。

Queue details

后续步骤

请参阅以下文档和示例: