快速入門:適用於 JavaScript 的 Azure 佇列儲存體用戶端程式庫

開始使用適用於 JavaScript 的 Azure 佇列儲存體用戶端程式庫。 Azure 佇列儲存體是用來儲存大量訊息的服務,以便日後擷取和處理。 請遵循下列步驟來安裝套件,並試用基本工作的程式碼範例。

API 參考文件 | 程式庫來源程式碼 | 套件 (npm) | 範例

使用適用於 JavaScript 的 Azure 佇列儲存體用戶端程式庫:

  • 建立佇列
  • 將訊息新增至佇列
  • 窺視佇列中的訊息
  • 更新佇列中的訊息
  • 取得佇列長度
  • 從佇列接收訊息
  • 刪除佇列中的訊息
  • 刪除佇列

必要條件

設定

本節會引導您準備專案以搭配適用於 JavaScript 的 Azure 佇列儲存體用戶端程式庫使用。

建立專案

建立名為 queues-quickstart 的 Node.js 應用程式。

  1. 在主控台視窗 (例如 cmd、PowerShell 或 Bash) 中,為專案建立一個新目錄:

    mkdir queues-quickstart
    
  2. 切換至新建立的 queues-quickstart 目錄:

    cd queues-quickstart
    
  3. 建立 package.json 檔案:

    npm init -y
    
  4. 在 Visual Studio Code 中開啟專案:

    code .
    

安裝套件

從專案目錄中,使用 npm install 命令安裝下列套件。

  1. 安裝 Azure 佇列儲存體 npm 套件:

    npm install @azure/storage-queue
    
  2. 安裝 Azure 身分識別 npm 套件以支援無密碼連線:

    npm install @azure/identity
    
  3. 安裝此快速入門中用到的其他相依項目:

    npm install uuid dotenv
    

設定應用程式架構

從專案目錄:

  1. 在程式碼編輯器中開啟新的文字檔

  2. 加入 require 呼叫以載入 Azure 和 Node.js 模組

  3. 建立程式的結構,包括基本例外狀況處理

    程式碼如下:

    const { QueueClient } = require("@azure/storage-queue");
    const { DefaultAzureCredential } = require('@azure/identity');
    const { v1: uuidv1 } = require("uuid");
    
    async function main() {
        console.log("Azure Queue Storage client library - JavaScript quickstart sample");
    
        // Quickstart code goes here
    }
    
    main().then(() => console.log("\nDone")).catch((ex) => console.log(ex.message));
    
    
  4. 將新檔案以 index.js 儲存在 queues-quickstart 目錄中。

向 Azure 驗證

大部分 Azure 服務的應用程式要求都必須獲得授權。 在程式碼中實作對 Azure 服務的無密碼連線時,建議使用 Azure 身分識別用戶端程式庫提供的 DefaultAzureCredential 類別。

您也可以直接使用密碼、連接字串或其他認證來授權對 Azure 服務的要求。 不過,應該謹慎使用此方法。 開發人員必須盡可能避免在不安全的地方公開秘密。 能夠取得密碼或祕密金鑰存取的任何人都可以進行驗證。 DefaultAzureCredential 提供優於帳戶金鑰的管理和安全性優點,允許無密碼驗證。 下列範例示範這兩個選項。

DefaultAzureCredential 是適用於 JavaScript 的 Azure 身分識別用戶端程式庫所提供的類別。 如需深入了解 DefaultAzureCredential,請參閱 DefaultAzureCredential 概觀DefaultAzureCredential 支援多個驗證方法,並在執行階段判斷應該使用哪個方法。 此方法可讓您的應用程式在不同的環境中 (本機或實際執行環境) 使用不同的驗證方法,而不需要實作環境特有的程式碼。

例如,您的應用程式可以在本機開發時使用 Azure CLI 登入認證進行驗證,然後在部署至 Azure 之後,使用 受控識別。 此轉移不需要變更程式碼。

在本機開發時,請確定存取佇列資料的使用者帳戶具有正確的權限。 您將需要 儲存體佇列資料參與者 才能讀取和寫入佇列資料。 若要指派此角色給您自己,您需要被指派使用者存取管理員角色,或另一個包含 Microsoft.Authorization/roleAssignments/write 動作的角色。 您可以使用 Azure 入口網站、Azure CLI 或 Azure PowerShell,將 Azure RBAC 角色指派給使用者。 您可以在範圍概觀頁面上深入了解角色指派的可用範圍。

在此案例中,您會將權限指派給使用者帳戶 (以儲存體帳戶為範圍),以遵循最低權限原則。 此做法只為使用者提供所需的最低權限,並建立更安全的實際執行環境。

下列範例將 儲存體佇列資料參與者 角色指派給使用者帳戶,以針對儲存體帳戶中的佇列資料提供讀取和寫入存取權。

重要

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

  1. 在 Azure 入口網站中,使用主要搜尋列或左側導覽找出您的儲存體帳戶。

  2. 在儲存體帳戶概觀頁面上,從左側功能表中選取 [存取控制 (IAM)]

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

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

A screenshot showing how to assign a role.

  1. 使用搜尋方塊,從結果篩選出所需的角色。 在此範例中,搜尋儲存體佇列資料參與者,接著選取相符的結果,然後選擇 下一步

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

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

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

物件模型

Azure 佇列儲存體是用來儲存大量訊息的服務。 一則佇列訊息的大小可能高達 64 KB。 一則佇列可包含數百則訊息,最高為儲存體帳戶的容量總計限制。 佇列通常用來建立工作待辦項目,以非同步處理。 佇列儲存體提供三種類型資源:

  • 儲存體帳戶:已透過儲存體帳戶完成所有 Azure 儲存體的存取。 如需儲存體帳戶的詳細資訊,請參閱 儲存體帳戶概觀
  • 佇列:佇列包含一組訊息。 所有訊息都必須在佇列中。 請注意,佇列名稱必須全部小寫。 如需為佇列命名的詳細資訊,請參閱 為佇列和中繼資料命名
  • 訊息:大小上限為 64 KB 的訊息 (任何格式)。 訊息可保留在佇列中的時間上限為 7 天。 在 2017-07-29 版或更新版本中,存留時間上限可以是任何正數或 -1 (表示訊息不會過期)。 如果省略此參數,則預設存留時間為七天。

下圖顯示資源之間的關係。

Diagram of Queue storage architecture

使用下列 JavaScript 類別與這些資源互動:

  • QueueServiceClientQueueServiceClient 執行個體代表 Azure 儲存體佇列服務中指定儲存體帳戶的連線。 此用戶端可讓您管理儲存體帳戶中的所有佇列。
  • QueueClientQueueClient 執行個體代表儲存體帳戶中的單一佇列。 此用戶端可讓您管理和操作個別佇列及其訊息。

程式碼範例

這些範例程式碼片段會示範如何使用適用於 JavaScript 的 Azure 佇列儲存體用戶端程式庫執行下列動作:

授權存取並建立用戶端物件

請確定使用您指派角色的相同 Microsoft Entra 帳戶進行驗證。 您可以透過 Azure CLI、Visual Studio Code 或 Azure PowerShell 進行驗證。

使用下列命令透過 Azure CLI 登入 Azure:

az login

驗證之後,您可以使用 DefaultAzureCredential 來建立和授權 QueueClient 物件,以存取記憶體帳戶中的佇列資料。 DefaultAzureCredential 會自動探索並使用您在上一個步驟中用來登入的帳戶。

若要使用 DefaultAzureCredential 授權,請確定您已新增 @azure/identity 套件,如 安裝套件 中所述。 此外,請務必在 index.js 檔案中載入 @azure/identity 模組:

const { DefaultAzureCredential } = require('@azure/identity');

決定佇列的名稱,並使用 DefaultAzureCredential 進行授權,建立 QueueClient 類別的執行個體。 我們會使用此用戶端物件來建立並與儲存體帳戶中的佇列資源互動。

重要

佇列名稱只能包含小寫字母、數字和連字號,且必須以字母或數字開頭。 每個連字號前後都必須緊接非連字號的字元。 名稱長度也必須為 3 到 63 個字元。 如需為佇列命名的詳細資訊,請參閱為佇列和中繼資料命名

main 方法內新增下列程式碼,並確定取代 <storage-account-name> 預留位置值:

// Create a unique name for the queue
const queueName = "quickstart" + uuidv1();

// Instantiate a QueueClient which will be used to create and interact with a queue
// TODO: replace <storage-account-name> with the actual name
const queueClient = new QueueClient(`https://<storage-account-name>.queue.core.windows.net/${queueName}`, new DefaultAzureCredential());

注意

您使用 QueueClient 類別傳送的訊息,必須採用可以包含在以 UTF-8 編碼的 XML 要求中的格式。 若要在訊息中加入標記,訊息內容必須是 XML 逸出格式或 Base64 編碼格式。

佇列訊息會儲存為字串。 如果您需要傳送不同的資料類型,您必須在傳送訊息時將該資料類型序列化為字串,並在讀取訊息時還原序列化字串格式。

若要將 JSON 轉換為字串格式,並在 Node.js 中再次轉回,請使用下列協助程式函數:

function jsonToBase64(jsonObj) {
    const jsonString = JSON.stringify(jsonObj)
    return  Buffer.from(jsonString).toString('base64')
}
function encodeBase64ToJson(base64String) {
    const jsonString = Buffer.from(base64String,'base64').toString()
    return JSON.parse(jsonString)
}

建立佇列

使用 QueueClient 物件,呼叫 create 方法來在儲存體帳戶中建立佇列。

將此程式碼加入到 main 方法的結尾處:

console.log("\nCreating queue...");
console.log("\t", queueName);

// Create the queue
const createQueueResponse = await queueClient.create();
console.log("Queue created, requestId:", createQueueResponse.requestId);

將訊息新增至佇列

下列程式碼片段會藉由呼叫 sendMessage 方法,將訊息新增至佇列。 其也會儲存第三次 sendMessage 呼叫所傳回的 QueueSendMessageResponse。 傳回的 sendMessageResponse 用來在稍後的程式中更新訊息內容。

將此程式碼加入到 main 函式的結尾處:

console.log("\nAdding messages to the queue...");

// Send several messages to the queue
await queueClient.sendMessage("First message");
await queueClient.sendMessage("Second message");
const sendMessageResponse = await queueClient.sendMessage("Third message");

console.log("Messages added, requestId:", sendMessageResponse.requestId);

窺視佇列中的訊息

藉由呼叫 peekMessages 方法來窺視佇列中的訊息。 此方法會從佇列前面擷取一或多則訊息,但不會更改訊息的可見性。 根據預設,peekMessages 會瞄核單一訊息。

將此程式碼加入到 main 函式的結尾處:

console.log("\nPeek at the messages in the queue...");

// Peek at messages in the queue
const peekedMessages = await queueClient.peekMessages({ numberOfMessages : 5 });

for (i = 0; i < peekedMessages.peekedMessageItems.length; i++) {
    // Display the peeked message
    console.log("\t", peekedMessages.peekedMessageItems[i].messageText);
}

更新佇列中的訊息

藉由呼叫 updateMessage 方法來更新訊息的內容。 此方法可以變更訊息的可見度逾時和內容。 訊息內容必須是大小上限為 64 KB 的 UTF-8 編碼字串。 連同新內容,傳入先前在程式碼中儲存的回應中的 messageIdpopReceiptsendMessageResponse 屬性會識別要更新的訊息。

console.log("\nUpdating the third message in the queue...");

// Update a message using the response saved when calling sendMessage earlier
updateMessageResponse = await queueClient.updateMessage(
    sendMessageResponse.messageId,
    sendMessageResponse.popReceipt,
    "Third message has been updated"
);

console.log("Message updated, requestId:", updateMessageResponse.requestId);

取得佇列長度

getProperties 方法會傳回佇列的中繼資料,包括在佇列中等待的大約訊息數目。

const properties = await queueClient.getProperties();
console.log("Approximate queue length: ", properties.approximateMessagesCount);

從佇列接收訊息

藉由呼叫 receiveMessages 方法來下載先前新增的訊息。 在 numberOfMessages 欄位中,傳入要針對此呼叫接收的訊息數目上限。

將此程式碼加入到 main 函式的結尾處:

console.log("\nReceiving messages from the queue...");

// Get messages from the queue
const receivedMessagesResponse = await queueClient.receiveMessages({ numberOfMessages : 5 });

console.log("Messages received, requestId:", receivedMessagesResponse.requestId);

呼叫 receiveMessages 方法時,您可以選擇性地在 QueueReceiveMessageOptions 中指定值,以自訂訊息擷取。 您可以為 numberOfMessages 指定值,這是要從佇列擷取的訊息數目。 預設值為 1 則訊息,最大值為 32 則訊息。 您也可以為 visibilityTimeout 指定值,以隱藏逾時期間其他作業的訊息。 預設值為 30 秒。

刪除佇列中的訊息

您可以在接收和處理訊息後,從佇列中刪除訊息。 在此情況下,處理只會在主控台上顯示訊息。

藉由呼叫 deleteMessage 方法來刪除訊息。 任何未明確刪除的訊息最後都會再次顯示在佇列中,以提供另一次進行處理的機會。

將此程式碼加入到 main 函式的結尾處:

// 'Process' and delete messages from the queue
for (i = 0; i < receivedMessagesResponse.receivedMessageItems.length; i++) {
    receivedMessage = receivedMessagesResponse.receivedMessageItems[i];

    // 'Process' the message
    console.log("\tProcessing:", receivedMessage.messageText);

    // Delete the message
    const deleteMessageResponse = await queueClient.deleteMessage(
        receivedMessage.messageId,
        receivedMessage.popReceipt
    );
    console.log("\tMessage deleted, requestId:", deleteMessageResponse.requestId);
}

刪除佇列

下列程式碼會使用 delete 方法刪除佇列,以清除應用程式所建立的資源。

將此程式碼新增到 main 函式的結尾並儲存檔案:

// Delete the queue
console.log("\nDeleting queue...");
const deleteQueueResponse = await queueClient.delete();
console.log("Queue deleted, requestId:", deleteQueueResponse.requestId);

執行程式碼

此應用程式會建立三則訊息,並將其新增至 Azure 佇列。 程式碼會列出佇列中的訊息,然後在最後刪除佇列之前,先擷取並刪除訊息。

在主控台視窗中,瀏覽至包含 index.js 檔案的目錄,然後執行下列 node 命令來執行應用程式。

node index.js

應用程式的輸出類似下列範例:

Azure Queue Storage client library - JavaScript quickstart sample

Creating queue...
         quickstart<UUID>
Queue created, requestId: 5c0bc94c-6003-011b-7c11-b13d06000000

Adding messages to the queue...
Messages added, requestId: a0390321-8003-001e-0311-b18f2c000000

Peek at the messages in the queue...
         First message
         Second message
         Third message

Updating the third message in the queue...
Message updated, requestId: cb172c9a-5003-001c-2911-b18dd6000000

Receiving messages from the queue...
Messages received, requestId: a039036f-8003-001e-4811-b18f2c000000
        Processing: First message
        Message deleted, requestId: 4a65b82b-d003-00a7-5411-b16c22000000
        Processing: Second message
        Message deleted, requestId: 4f0b2958-c003-0030-2a11-b10feb000000
        Processing: Third message has been updated
        Message deleted, requestId: 6c978fcb-5003-00b6-2711-b15b39000000

Deleting queue...
Queue deleted, requestId: 5c0bca05-6003-011b-1e11-b13d06000000

Done

使用偵錯工具逐步執行程式碼,並在整個過程中檢查您的 Azure 入口網站。 檢查您的儲存體帳戶,確認已建立並刪除佇列中的訊息。

下一步

在本快速入門中,您已了解如何使用 JavaScript 程式碼建立佇列,並將訊息新增至其中。 然後您會了解如何窺視、擷取和刪除訊息。 最後,您會了解如何刪除訊息佇列。

如需教學課程、範例、快速入門及其他文件,請瀏覽: