將訊息傳送至 Azure 服務匯流排 佇列並從中接收訊息 (JavaScript)

在本教學課程中,您會完成下列步驟:

  1. 使用 Azure 入口網站 建立 服務匯流排 命名空間。
  2. 使用 Azure 入口網站 建立 服務匯流排 佇列。
  3. 撰寫 JavaScript 應用程式以使用 @azure/服務總線 套件來:
    1. 將一組訊息傳送至佇列。
    2. 從佇列接收這些訊息。

注意

本快速入門提供將訊息傳送至 服務匯流排 佇列並接收訊息的簡單案例的逐步指示。 您可以在 GitHub 上的 Azure SDK for JavaScript 存放庫中找到適用於 Azure 服務匯流排 的預先建置 JavaScript 和 TypeScript 範例。

必要條件

如果您不熟悉服務,請先參閱 服務匯流排 概觀,再執行本快速入門。

若要搭配您自己的 Azure 帳戶使用此快速入門,您需要:

  • 安裝 Azure CLI,其可為開發人員電腦提供無密碼驗證。
  • 在終端機或命令提示字元 az login中使用 您的 Azure 帳戶登入。
  • 當您將適當的數據角色新增至資源時,請使用相同的帳戶。
  • 在相同的終端機或命令提示字元中執行程序代碼。
  • 記下 服務匯流排 命名空間的佇列名稱。 您需要在程式代碼中。

注意

本教學課程適用於您可以使用 Nodejs 複製和執行 範例。 如需如何建立Node.js應用程式的指示,請參閱使用 Windows PowerShell 建立和部署Node.js應用程式至 Azure 網站或Node.js雲端服務。

在 Azure 入口網站 中建立命名空間

若要開始在 Azure 中使用 服務匯流排 傳訊實體,您必須先建立命名空間,其名稱在 Azure 中是唯一的。 命名空間提供應用程式內 服務匯流排 資源(佇列、主題等)的範圍容器。

若要建立命名空間:

  1. 登入 Azure 入口網站

  2. 流覽至 [ 所有服務] 頁面

  3. 在左側導覽列上,從類別清單中選取 [整合],將滑鼠停留在 服務匯流排 上方,然後選取 + 服務匯流排 圖格上的按鈕。

    Image showing selection of Create a resource, Integration, and then Service Bus in the menu.

  4. 在 [建立命名空間] 頁面的 [基本] 標籤中,遵循下列步驟:

    1. 針對 [ 訂用帳戶],選擇要在其中建立命名空間的 Azure 訂用帳戶。

    2. 針對 [ 資源群組],選擇命名空間將存留在其中的現有資源群組,或建立新的資源群組。

    3. 輸入命名空間的名稱。 命名空間名稱應遵守下列命名慣例:

      • 名稱在整個 Azure 中必須是唯一的。 系統會立即檢查此名稱是否可用。
      • 名稱長度至少為 6,最多 50 個字元。
      • 名稱只能包含字母、數位、連字元 “-”。
      • 名稱必須以字母開頭,並以字母或數字結尾。
      • 名稱結尾不是 “-sb” 或 “-mgmt”。
    4. 針對 [ 位置],選擇您的命名空間應該裝載所在的區域。

    5. 針對 [定價層],選取命名空間的定價層 [基本]、[標準] 或 [進階版]。 在本快速入門中,選取 [ 標準]。

      重要

      如果您想要使用主題和訂帳戶,請選擇 [標準] 或 [進階版]。 基本定價層不支援主題/訂用帳戶。

      如果您選取 進階版 定價層,請指定傳訊單位數目。 進階層會在 CPU 和記憶體層級提供資源隔離,讓每個工作負載以隔離方式執行。 此資源容器稱為傳訊單位。 進階命名空間至少有一個傳訊單位。 您可以為每個 服務匯流排 進階版 命名空間選取 1、2、4、8 或 16 個傳訊單位。 如需詳細資訊,請參閱傳訊 服務匯流排 進階版。

    6. 選取頁面底部的 [檢閱 + 建立] 。

      Image showing the Create a namespace page

    7. 在 [檢閱 + 建立] 頁面上檢閱設定,然後選取 [建立]

  5. 部署資源成功后,請選取 部署頁面上的 [移至資源 ]。

    Image showing the deployment succeeded page with the Go to resource link.

  6. 您會看到服務總線命名空間的首頁。

    Image showing the home page of the Service Bus namespace created.

在 Azure 入口網站 中建立佇列

  1. [服務匯流排 命名空間] 頁面上,選取左側導覽功能表中的 [佇列]。

  2. 在 [ 佇列] 頁面上,選取 工具列上的 [+ 佇列 ]。

  3. 輸入佇列的名稱,並將其他值保留預設值。

  4. 現在,選取 [ 建立]。

    Image showing creation of a queue in the portal

向 Azure 驗證應用程式

本快速入門說明連線到 Azure 服務匯流排的兩種方式:密碼和 連接字串

第一個選項示範如何使用 Microsoft Entra ID 和角色型存取控制 (RBAC) 中的安全性主體來連線到 服務匯流排 命名空間。 您不需要擔心在程式代碼或組態檔中,或在 Azure 金鑰保存庫 等安全記憶體中硬式編碼 連接字串。

第二個選項示範如何使用 連接字串 來連線到 服務匯流排 命名空間。 如果您不熟悉 Azure,您可能會發現 連接字串 選項更容易遵循。 我們建議在真實世界應用程式和生產環境中使用無密碼選項。 如需詳細資訊,請參閱驗證與授權。 您也可以在概 觀頁面上深入瞭解無密碼驗證。

將角色指派給 Microsoft Entra 使用者

在本機開發時,請確定連線到 Azure 服務匯流排 的用戶帳戶具有正確的許可權。 您需要 Azure 服務匯流排 數據擁有者角色,才能傳送和接收訊息。 若要指派此角色,您需要使用者存取 管理員 istrator 角色,或包含Microsoft.Authorization/roleAssignments/write動作的另一個角色。 您可以使用 Azure 入口網站、Azure CLI 或 Azure PowerShell,將 Azure RBAC 角色指派給使用者。 在範圍概觀頁面上深入瞭解角色指派的可用範圍。

下列範例會將Azure Service Bus Data Owner角色指派給您的用戶帳戶,以提供 Azure 服務匯流排 資源的完整存取權。 在實際案例中,遵循 最低許可權 原則,只為使用者提供更安全的生產環境所需的最低許可權。

適用於 Azure 服務匯流排的 Azure 內建角色

針對 Azure 服務匯流排,透過 Azure 入口網站 和 Azure 資源管理 API 來管理命名空間和所有相關資源,已使用 Azure RBAC 模型加以保護。 Azure 提供下列 Azure 內建角色,以授權存取 服務匯流排 命名空間:

如果您想要建立自定義角色,請參閱 服務匯流排 作業所需的許可權。

將 Microsoft Entra 使用者新增至 Azure 服務匯流排 擁有者角色

將 Microsoft Entra 使用者名稱新增至 服務匯流排 命名空間層級 Azure 服務匯流排 數據擁有者角色。 它可讓在使用者帳戶內容中執行的應用程式將訊息傳送至佇列或主題,以及接收來自佇列或主題訂用帳戶的訊息。

重要

在大部分情況下,在 Azure 中傳播角色指派需要一兩分鐘的時間。 在罕見的情況下,最多可能需要 八分鐘的時間。 如果您第一次執行程式碼時收到驗證錯誤,請稍候片刻再試一次。

  1. 如果您沒有在 Azure 入口網站 中開啟 [服務匯流排 命名空間] 頁面,請使用主要搜尋列或左側導覽來尋找您的 服務匯流排 命名空間。

  2. 在 [概觀] 頁面上,從左側功能表中選取 [訪問控制][IAM ]。

  3. 在 [存取控制 (IAM)] 頁面上,選取 [角色指派] 索引標籤。

  4. 從頂端功能表選取 [+ 新增],然後從產生的下拉功能表中選取 [新增角色指派]

    A screenshot showing how to assign a role.

  5. 使用搜尋方塊,從結果篩選出所需的角色。 在此範例中,搜尋 Azure Service Bus Data Owner 並選取相符的結果。 接著,選擇 [下一步]

  6. 在 [存取權指派對象為] 下,選取 [使用者、群組或服務主體],然後選擇 [+ 選取成員]

  7. 在對話方塊中,搜尋 Microsoft Entra 使用者名稱 (通常是您的 user@domain 電子郵件地址),然後在對話方塊底部選擇 [選取]

  8. 選取 [檢閱 + 指派] 以移至最終頁面,然後再次選取 [檢閱 + 指派] 以完成此程序。

使用 Node 封裝管理員 (NPM) 安裝套件

  1. 若要安裝 服務匯流排 所需的 npm 套件,請開啟路徑中具有 npm 的命令提示字元,將目錄變更為您要擁有範例的資料夾,然後執行此命令。

  2. 安裝下列套件:

    npm install @azure/service-bus @azure/identity
    

傳送訊息至佇列

下列範例程式代碼示範如何將訊息傳送至佇列。

您必須已使用 Azure CLI az login 登入,才能讓本機電腦提供此程式碼中所需的無密碼驗證。

  1. 開啟您最愛的編輯器,例如 Visual Studio Code

  2. 建立名為 send.js 的檔案,並將下列程式代碼貼到其中。 此程式代碼會將科學家的名稱當做訊息傳送至您的佇列。

    重要

    無密碼認證隨附 DefaultAzureCredential

    const { ServiceBusClient } = require("@azure/service-bus");
    const { DefaultAzureCredential } = require("@azure/identity");
    
    // Replace `<SERVICE-BUS-NAMESPACE>` with your namespace
    const fullyQualifiedNamespace = "<SERVICE-BUS-NAMESPACE>.servicebus.windows.net";
    
    // Passwordless credential
    const credential = new DefaultAzureCredential();
    
    // 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 passwordless authentication to the Service Bus namespace
        const sbClient = new ServiceBusClient(fullyQualifiedNamespace, credential);
    
        // 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. 將取代<SERVICE-BUS-NAMESPACE>為您的 服務匯流排 命名空間。

  4. 將取代 <QUEUE NAME> 為佇列的名稱。

  5. 然後在命令提示字元中執行 命令,以執行此檔案。

    node send.js
    
  6. 您應該會看見下列輸出。

    Sent a batch of messages to the queue: myqueue
    

從佇列接收訊息

您必須已使用 Azure CLI az login 登入,才能讓本機電腦提供此程式碼中所需的無密碼驗證。

  1. 開啟您慣用的編輯器,例如 Visual Studio Code

  2. 建立名為 receive.js 的檔案,並將下列程式代碼貼入其中。

    const { delay, ServiceBusClient, ServiceBusMessage } = require("@azure/service-bus");
    const { DefaultAzureCredential } = require("@azure/identity");
    
    // Replace `<SERVICE-BUS-NAMESPACE>` with your namespace
    const fullyQualifiedNamespace = "<SERVICE-BUS-NAMESPACE>.servicebus.windows.net";
    
    // Passwordless credential
    const credential = new DefaultAzureCredential();
    
    // name of the queue
    const queueName = "<QUEUE NAME>"
    
     async function main() {
        // create a Service Bus client using the passwordless authentication to the Service Bus namespace
        const sbClient = new ServiceBusClient(fullyQualifiedNamespace, credential);
    
        // 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. 以您的 服務匯流排 命名空間取代 <SERVICE-BUS-NAMESPACE>

  4. 將取代 <QUEUE NAME> 為佇列的名稱。

  5. 然後在命令提示字元中執行 命令,以執行此檔案。

    node receive.js
    

您應該會看見下列輸出。

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

疑難排解

如果您在執行 JavaScript 程式代碼的無 密碼版本時收到下列其中一個錯誤,請確定您已透過 Azure CLI 命令登入, az login 並將 適當的角色 套用至您的 Azure 使用者帳戶:

  • 執行此作業需要 'Send' 宣告(s)
  • 執行此作業需要 'Receive' 宣告(s)

清除資源

流覽至 Azure 入口網站 中的 服務匯流排 命名空間,然後在 Azure 入口網站 上選取 [刪除],以刪除命名空間及其中的佇列。

下一步

請參閱下列檔和範例: