在 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

注意

使用 Node Package Manager (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.

  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. 此程式碼會將訊息傳送至您的佇列。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 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> 取代為服務匯流排命名空間的連接字串。Replace <CONNECTION STRING TO SERVICE BUS NAMESPACE> with the connection string to your Service Bus namespace.

  4. <QUEUE NAME> 取代為佇列名稱。Replace <QUEUE NAME> with the name of the queue.

  5. 然後,在命令提示字元中執行命令,以執行此檔案。Then run the command in a command prompt to execute this file.

    node send.js 
    
  6. 您應該會看見下列輸出。You should see the following output.

    Sent a batch of messages to the queue: myqueue
    

從佇列接收訊息Receive messages from a queue

  1. 開啟您慣用的編輯器,例如 Visual Studio CodeOpen your favorite editor, such as Visual Studio Code

  2. 建立名為 receive.js 的檔案,並將以下程式碼貼在該檔案內。Create a file called receive.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);
     });
    
  3. <CONNECTION STRING TO SERVICE BUS NAMESPACE> 取代為服務匯流排命名空間的連接字串。Replace <CONNECTION STRING TO SERVICE BUS NAMESPACE> with the connection string to your Service Bus namespace.

  4. <QUEUE NAME> 取代為佇列名稱。Replace <QUEUE NAME> with the name of the queue.

  5. 然後,在命令提示字元中執行命令,以執行此檔案。Then, run the command in a command prompt to execute this file.

    node receive.js
    
  6. 您應該會看見下列輸出。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: