共用方式為


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

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

API 參考文件 | 程式庫原始碼 | 封裝 (Maven) | 範例

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

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

先決條件

設定

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

建立專案

建立名為 queues-quickstart 的 Java 應用程式。

  1. 在主控台視窗 (例如 cmd、PowerShell 或 Bash) 中,使用 Maven 建立名稱為 queues-quickstart 的新主控台應用程式。 輸入以下 mvn 命令以創建“Hello,world!Java 專案。

    mvn archetype:generate `
        --define interactiveMode=n `
        --define groupId=com.queues.quickstart `
        --define artifactId=queues-quickstart `
        --define archetypeArtifactId=maven-archetype-quickstart `
        --define archetypeVersion=1.4
    
  2. 產生專案的輸出應該如下所示:

    [INFO] Scanning for projects...
    [INFO]
    [INFO] ------------------< org.apache.maven:standalone-pom >-------------------
    [INFO] Building Maven Stub Project (No POM) 1
    [INFO] --------------------------------[ pom ]---------------------------------
    [INFO]
    [INFO] >>> maven-archetype-plugin:3.1.2:generate (default-cli) > generate-sources @ standalone-pom >>>
    [INFO]
    [INFO] <<< maven-archetype-plugin:3.1.2:generate (default-cli) < generate-sources @ standalone-pom <<<
    [INFO]
    [INFO]
    [INFO] --- maven-archetype-plugin:3.1.2:generate (default-cli) @ standalone-pom ---
    [INFO] Generating project in Batch mode
    [INFO] ----------------------------------------------------------------------------
    [INFO] Using following parameters for creating project from Archetype: maven-archetype-quickstart:1.4
    [INFO] ----------------------------------------------------------------------------
    [INFO] Parameter: groupId, Value: com.queues.quickstart
    [INFO] Parameter: artifactId, Value: queues-quickstart
    [INFO] Parameter: version, Value: 1.0-SNAPSHOT
    [INFO] Parameter: package, Value: com.queues.quickstart
    [INFO] Parameter: packageInPathFormat, Value: com/queues/quickstart
    [INFO] Parameter: version, Value: 1.0-SNAPSHOT
    [INFO] Parameter: package, Value: com.queues.quickstart
    [INFO] Parameter: groupId, Value: com.queues.quickstart
    [INFO] Parameter: artifactId, Value: queues-quickstart
    [INFO] Project created from Archetype in dir: C:\quickstarts\queues\queues-quickstart
    [INFO] ------------------------------------------------------------------------
    [INFO] BUILD SUCCESS
    [INFO] ------------------------------------------------------------------------
    [INFO] Total time:  6.394 s
    [INFO] Finished at: 2019-12-03T09:58:35-08:00
    [INFO] ------------------------------------------------------------------------
    
  3. 切換至新建立的 queues-quickstart 目錄。

    cd queues-quickstart
    

安裝套件

在文字編輯器中開啟 pom.xml 檔案。

新增 azure-sdk-bom 以取得最新版本的程式庫相依性。 在下列程式碼片段中,將{bom_version_to_target}預留位置替換為版本號碼。 使用 azure-sdk-bom 可讓您不必指定每個個別相依性的版本。 若要深入瞭解 BOM,請參閱 Azure SDK BOM 自述文件

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>com.azure</groupId>
            <artifactId>azure-sdk-bom</artifactId>
            <version>{bom_version_to_target}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

然後,將下列相依性元素新增至相依性群組。 需要 azure-identity 相依性才能對 Azure 服務進行無密碼連線。

<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-storage-queue</artifactId>
</dependency>
<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-identity</artifactId>
</dependency>

設定應用程式架構

從專案目錄:

  1. 導覽至 /src/main/java/com/queues/quickstart 目錄
  2. 在編輯器中開啟 App.java 檔案
  3. 刪除 System.out.println("Hello, world"); 陳述式
  4. 新增 import 指令

程式碼如下:

package com.queues.quickstart;

/**
 * Azure Queue Storage client library quickstart
 */
import com.azure.identity.*;
import com.azure.storage.queue.*;
import com.azure.storage.queue.models.*;
import java.io.*;

public class App
{
    public static void main(String[] args) throws IOException
    {
        // Quickstart code goes here
    }
}

向 Azure 驗證

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

您也可以直接使用密碼、連接字串或其他認證來授權對 Azure 服務的要求。 但是,應謹慎使用這種方法。 開發人員必須勤奮,永遠不要在不安全的位置暴露這些秘密。 任何獲得密碼或密鑰訪問權限的人都可以進行身份驗證。 DefaultAzureCredential 提供比帳戶金鑰更好的管理和安全優勢,以允許無密碼驗證。 下列範例示範這兩個選項。

DefaultAzureCredential 是適用於 Java 的 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. 從頂端功能表中選取 [+ 新增 ],然後從產生的下拉式功能表中選取 [ 新增角色指派 ]。

顯示如何指派角色的螢幕擷取畫面。

  1. 使用搜尋方塊,從結果篩選出所需的角色。 在此範例中,搜尋 Storage Queue Data Contributor 並選取相符的結果,然後選擇 Next (下一步)。

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

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

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

物件模型

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

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

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

佇列儲存體架構圖

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

程式碼範例

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

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

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

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

az login

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

若要授權使用 DefaultAzureCredential,請確定您已在 中新增 pom.xml 相依性,如 安裝套件 所述。 此外,請務必在com.azure.identity檔案中新增匯入指令:

import com.azure.identity.*;

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

這很重要

佇列名稱只能包含小寫字母、數字和連字號,而且必須以字母或數字開頭。 每個連字號之前和後面都必須有一個非連字號字元。 名稱的長度也必須介於 3 到 63 個字元之間。 如需命名佇列的相關資訊,請參閱 命名佇列和 meta 資料

請將此程式碼新增至 main 方法中,並確保將 <storage-account-name> 佔位符的值替換掉。

System.out.println("Azure Queue Storage client library - Java quickstart sample\n");

// Create a unique name for the queue
String queueName = "quickstartqueues-" + java.util.UUID.randomUUID();

// Instantiate a QueueClient
// We'll use this client object to create and interact with the queue
// TODO: replace <storage-account-name> with the actual name
QueueClient queueClient = new QueueClientBuilder()
        .endpoint("https://<storage-account-name>.queue.core.windows.net/")
        .queueName(queueName)
        .credential(new DefaultAzureCredentialBuilder().build())
        .buildClient();

備註

使用類別 QueueClient 傳送的訊息必須採用可包含在具有 UTF-8 編碼的 XML 要求中的格式。 您可以選擇性地將 QueueMessageEncoding 選項設定為 處理 BASE64 不符合規範的訊息。

建立佇列

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

將以下程式碼新增至方法的 main 末尾:

System.out.println("Creating queue: " + queueName);

// Create the queue
queueClient.create();

將訊息新增至佇列

下列程式碼片段會呼叫 sendMessage 方法,將訊息新增至佇列。 它也會儲存從 SendMessageResult 呼叫中返回的 sendMessage。 結果用於稍後在程式中更新訊息。

將以下程式碼新增至方法的 main 末尾:

System.out.println("\nAdding messages to the queue...");

// Send several messages to the queue
queueClient.sendMessage("First message");
queueClient.sendMessage("Second message");

// Save the result so we can update this message later
SendMessageResult result = queueClient.sendMessage("Third message");

查看佇列中的訊息

藉由呼叫 peekMessages 方法來窺視佇列中的訊息。 這個方法會從佇列前面擷取一或多個訊息,但不會變更訊息的可見度。

將以下程式碼新增至方法的 main 末尾:

System.out.println("\nPeek at the messages in the queue...");

// Peek at messages in the queue
queueClient.peekMessages(10, null, null).forEach(
    peekedMessage -> System.out.println("Message: " + peekedMessage.getMessageText()));

更新佇列中的訊息

使用updateMessage方法更新訊息的內容。 這個方法可以變更訊息的可見性逾時和內容。 訊息內容必須是大小不超過 64 KB 的 UTF-8 編碼字串。 連同訊息的新內容,使用先前在程式碼中儲存的 SendMessageResult,傳入訊息識別碼和 pop 回條。 訊息識別碼和 pop 回條可識別要更新的訊息。

System.out.println("\nUpdating the third message in the queue...");

// Update a message using the result that
// was saved when sending the message
queueClient.updateMessage(result.getMessageId(),
                          result.getPopReceipt(),
                          "Third message has been updated",
                          Duration.ofSeconds(1));

取得佇列長度

您可以取得佇列中訊息數目的估計值。

getProperties 方法會傳回數個值,包括目前佇列中的訊息數目。 計數只是近似值,因為可以在您的請求後添加或刪除消息。 getApproximateMessageCount 方法傳回由呼叫 getProperties 所擷取的最後一個值,而不需呼叫佇列儲存體。

QueueProperties properties = queueClient.getProperties();
long messageCount = properties.getApproximateMessagesCount();

System.out.println(String.format("Queue length: %d", messageCount));

從佇列接收及刪除訊息

可以透過呼叫 receiveMessages 方法來下載先前新增的訊息。 範例程式碼也會在接收和處理訊息之後從佇列中刪除訊息。 在此情況下,處理只是在主控台上顯示訊息。

應用程式會呼叫System.console().readLine();來暫停等待使用者輸入,然後再接收和刪除訊息。 在刪除資源之前,請在 Azure 入口網站 中確認已正確建立資源。 任何未明確刪除的訊息最終都會再次在佇列中可見,以便再次有機會處理它們。

將以下程式碼新增至方法的 main 末尾:

System.out.println("\nPress Enter key to receive messages and delete them from the queue...");
System.console().readLine();

// Get messages from the queue
queueClient.receiveMessages(10).forEach(
    // "Process" the message
    receivedMessage -> {
        System.out.println("Message: " + receivedMessage.getMessageText());

        // Let the service know we're finished with
        // the message and it can be safely deleted.
        queueClient.deleteMessage(receivedMessage.getMessageId(), receivedMessage.getPopReceipt());
    }
);

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

刪除佇列

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

將以下程式碼新增至方法的 main 末尾:

System.out.println("\nPress Enter key to delete the queue...");
System.console().readLine();

// Clean up
System.out.println("Deleting queue: " + queueClient.getQueueName());
queueClient.delete();

System.out.println("Done");

執行程式碼

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

在主控台視窗中,導覽至您的應用程式目錄,然後建置並執行應用程式。

mvn compile

然後,建置套件。

mvn package

使用下列 mvn 命令來執行應用程式。

mvn exec:java -Dexec.mainClass="com.queues.quickstart.App" -Dexec.cleanupDaemonThreads=false

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

Azure Queue Storage client library - Java quickstart sample

Adding messages to the queue...

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

Updating the third message in the queue...

Press Enter key to receive messages and delete them from the queue...

Message: First message
Message: Second message
Message: Third message has been updated

Press Enter key to delete the queue...

Deleting queue: quickstartqueues-fbf58f33-4d5a-41ac-ac0e-1a05d01c7003
Done

當應用程式在接收訊息之前暫停時,請在 Azure 入口網站 中檢查您的儲存體帳戶。 確認訊息是否在佇列中。

按 鍵 Enter 接收和刪除訊息。 出現提示時,再次按 鍵 Enter 刪除佇列並完成示範。

後續步驟

在本快速入門中,您已瞭解如何使用 Java 程式碼建立佇列,並將訊息新增至佇列。 然後你學會了查看、檢索和刪除訊息。 最後,您瞭解如何刪除訊息佇列。

如需教學課程、範例、快速入門和其他文件,請造訪: