次の方法で共有


Quickstart: Azure Queue Storage client library for Java

Get started with the Azure Queue Storage client library for Java. Azure Queue Storage は、後で取得して処理するために多数のメッセージを格納するためのサービスです。 以下の手順に従って、パッケージをインストールし、基本タスクのコード例を試してみましょう。

API reference documentation | Library source code | Package (Maven) | Samples

Use the Azure Queue Storage client library for Java to:

  • キューを作成する
  • メッセージをキューに追加する
  • キュー内のメッセージを表示する
  • キュー内のメッセージを更新する
  • キューの長さを取得する
  • キューからメッセージを受信する
  • キューからメッセージを削除する
  • キューを削除する

前提条件

セットアップ

This section walks you through preparing a project to work with the Azure Queue Storage client library for Java.

プロジェクトを作成する

Create a Java application named queues-quickstart.

  1. In a console window (such as cmd, PowerShell, or Bash), use Maven to create a new console app with the name queues-quickstart. Type the following mvn command to create a "Hello, world!" Java project.

    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. The output from generating the project should look something like this:

    [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
    

パッケージのインストール

Open the pom.xml file in your text editor.

Add azure-sdk-bom to take a dependency on the latest version of the library. In the following snippet, replace the {bom_version_to_target} placeholder with the version number. Using azure-sdk-bom keeps you from having to specify the version of each individual dependency. To learn more about the BOM, see the Azure SDK BOM README.

<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>

Then add the following dependency elements to the group of dependencies. The azure-identity dependency is needed for passwordless connections to Azure services.

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

アプリのフレームワークを設定する

プロジェクト ディレクトリで次の操作を行います。

  1. Navigate to the /src/main/java/com/queues/quickstart directory
  2. Open the App.java file in your editor
  3. Delete the System.out.println("Hello, world"); statement
  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 サービスに対するアプリケーション要求は、認可される必要があります。 コード内の Azure サービスに対してパスワードレス接続を実装するには、Azure ID クライアント ライブラリによって提供される DefaultAzureCredential クラスを使用する方法お勧めします。

パスワード、接続文字列、その他の資格情報を使用して、Azure サービスへの要求を直接承認することもできます。 ただし、この方法は慎重に使用する必要があります。 開発者は、安全でない場所にこれらのシークレットを公開しないように注意する必要があります。 パスワードまたはシークレット キーへのアクセス権を取得したユーザーは、誰でも認証を受けることができます。 DefaultAzureCredential はアカウント・キーよりも管理しやすく、セキュリティが優れており、パスワードレス認証が可能になります。 両方のオプションの例を次に示します。

DefaultAzureCredential is a class provided by the Azure Identity client library for Java. DefaultAzureCredential の詳細については、DefaultAzureCredential の概要を参照してください。 DefaultAzureCredential は複数の認証方法をサポートしており、実行時に使用する方法が決定されます。 このアプローチを採用すると、環境固有のコードを実装することなく、異なる環境 (ローカルと運用環境) で異なる認証方法をアプリに使用できます。

For example, your app can authenticate using your Azure CLI sign-in credentials when developing locally, and then use a managed identity once it has been deployed to Azure. この移行のためにコードを変更する必要はありません。

ローカルで開発する場合は、キュー データにアクセスするユーザー アカウントに正しいアクセス許可があることを確認します。 キュー データの読み取りと書き込みを行うには、ストレージ キュー データ共同作成者が必要です。 このロールを自分に割り当てるには、ユーザー アクセス管理者ロール、または Microsoft.Authorization/roleAssignments/write アクションを含む別のロールに割り当てられている必要があります。 Azure portal、Azure CLI、または Azure PowerShell を使用して、ユーザーに Azure RBAC ロールを割り当てることができます。 ロールの割り当てに使用できるスコープの詳細は、スコープの概要ページでご覧いただけます。

このシナリオでは、最小限の特権の原則に従って、ストレージ アカウントに限定したアクセス許可をユーザー アカウントに割り当てます。 この方法を使って、ユーザーに必要最小限のアクセス許可のみを与え、より安全な運用環境を作成します。

次の例では、ストレージ キュー データ共同作成者ロールを自分のユーザー アカウントに割り当てます。これにより、そのストレージ アカウント内のキュー データに対する読み取りと書き込みの両方のアクセス権が付与されます。

重要

ほとんどの場合、ロールの割り当てが Azure に反映されるまでの時間は 1 分から 2 分ですが、まれに 8 分程度までかかる場合があります。 初めてコードを実行したときに認証エラーを受け取る場合は、しばらく待ってから再試行してください。

  1. Azure portal で、メインの検索バーまたは左側のナビゲーションを使ってストレージ アカウントを見つけます。

  2. ストレージ アカウントの概要ページで、左側のメニューから [アクセス制御 (IAM)] を選びます。

  3. [アクセス制御 (IAM)] ページで、[ロールの割り当て] タブを選びます。

  4. 上部のメニューから [+ 追加] を選択し、次に結果のドロップダウン メニューから [ロールの割り当ての追加] を選択します。

ロールを割り当てる方法を示すスクリーンショット。

  1. 検索ボックスを使って、結果を目的のロールに絞り込みます。 この例では、「ストレージ キュー データ共同作成者」を検索し、一致する結果を選び、[次へ] を選びます。

  2. [アクセスの割り当て先] で、[ユーザー、グループ、またはサービス プリンシパル] を選び、[+ メンバーの選択] を選びます。

  3. ダイアログで、自分の Microsoft Entra ユーザー名 (通常は user@___domain メール アドレス) を検索し、ダイアログの下部にある [選択] を選びます。

  4. [レビューと割り当て] を選んで最終ページに移動し、もう一度 [レビューと割り当て] を行ってプロセスを完了します。

オブジェクト モデル

Azure Queue Storage は、大量のメッセージを格納するためのサービスです。 キュー メッセージのサイズは最大 64 KB です。 キューには、ストレージ アカウントの合計容量制限まで、数百万のメッセージが含まれる場合があります。 キューは、非同期的に処理する作業のバックログを作成するために一般的に使用されます。 Queue Storage には、次の 3 種類のリソースがあります。

  • ストレージ アカウント: Azure Storage にアクセスするときは必ずストレージ アカウントを使用します。 ストレージ アカウントの詳細については、「ストレージ アカウントの概要」を参照してください
  • キュー: キューは、メッセージのセットを格納します。 すべてのメッセージはキューに 格納されている必要があります。 キュー名は小文字で入力する必要があります。 キューの名前付け規則については、「 Naming Queues and Metadata (キューとメタデータの名前付け規則)」を参照してください。
  • メッセージ: 形式を問わず、メッセージのサイズは最大で 64 KB です。 メッセージは最大 7 日間キューに残ることができます。 バージョン 2017-07-29 以降では、最大有効期間を任意の正の数にすることができます。また、-1 は、メッセージが期限切れにならないことを示します。 このパラメーターを省略すると、既定の有効期間は 7 日になります。

次の図に、これらのリソースの関係を示します。

Queue storage のアーキテクチャ図

Use the following Java classes to interact with these resources:

  • QueueClientBuilder: The QueueClientBuilder class configures and instantiates a QueueClient object.
  • QueueServiceClient: QueueServiceClient を使用すると、ストレージ アカウント内のすべてのキューを管理できます。
  • QueueClient: QueueClient クラスを使用すると、個々のキューとそのメッセージを管理および操作できます。
  • QueueMessageItem: QueueMessageItem クラスは、キューに対して ReceiveMessages を呼び出したときに返される個々のオブジェクトを表します。

コード例

These example code snippets show you how to do the following actions with the Azure Queue Storage client library for Java:

アクセスの認可とクライアント オブジェクトの作成

ロールを割り当てたのと同じ Microsoft Entra アカウントで認証を受けるようにしてください。 Azure CLI、Visual Studio Code、または Azure PowerShell を使って認証することができます。

Azure CLI で次のコマンドを使って Azure にサインインします。

az login

認証が完了したら、QueueClient を使って、ストレージ アカウント内のキュー データにアクセスする DefaultAzureCredential オブジェクトを作成および認可できます。 DefaultAzureCredential は、前の手順でサインインしたアカウントを自動的に検出して使用します。

To authorize using DefaultAzureCredential, make sure you've added the azure-identity dependency in pom.xml, as described in Install the packages. Also, be sure to add an import directive for com.azure.identity in the App.java file:

import com.azure.identity.*;

キューの名前を決定し、認可に QueueClient を使って、DefaultAzureCredential クラスのインスタンスを作成します。 このクライアント オブジェクトを使って、ストレージ アカウント内のキュー リソースを作成して操作します。

重要

キュー名に使用できるのは小文字、数字、ハイフンのみであり、名前の先頭は文字または数字にする必要があります。 各ハイフンの前にハイフン以外の文字を付ける必要があります。 また、名前の長さは 3 ~ 63 文字にする必要があります。 キューの名前付けの詳細については、「キューとメタデータの名前付け」を参照してください。

Add this code inside the main method, and make sure to replace the <storage-account-name> placeholder value:

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();

Messages sent using the QueueClient class must be in a format that can be included in an XML request with UTF-8 encoding. You can optionally set the QueueMessageEncoding option to BASE64 to handle non-compliant messages.

キューを作成する

QueueClient オブジェクトを使い、create メソッドを呼び出してストレージ アカウントにキューを作成します。

Add this code to the end of the main method:

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

// Create the queue
queueClient.create();

メッセージをキューに追加する

以下のコード スニペットは、sendMessage メソッドを呼び出してキューにメッセージを追加します。 It also saves a SendMessageResult returned from a sendMessage call. The result is used to update the message later in the program.

Add this code to the end of the main method:

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 メソッドを呼び出します。 このメソッドは、キューの先頭からメッセージを 1 つ以上取得しますが、メッセージの可視性は変更しません。

Add this code to the end of the main method:

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 メソッドを呼び出します。 メッセージの表示タイムアウトと内容は、このメソッドで変更できます。 メッセージの内容には UTF-8 でエンコードされた文字列を指定してください。最大サイズは 64 KB です。 Along with new content for the message, pass in the message ID and pop receipt by using the SendMessageResult that was saved earlier in the code. The message ID and pop receipt identify which message to update.

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));

キューの長さを取得する

キュー内のメッセージ数の見積もりを取得できます。

The getProperties method returns several values including the number of messages currently in a queue. The count is only approximate because messages can be added or removed after your request. The getApproximateMessageCount method returns the last value retrieved by the call to getProperties, without calling Queue Storage.

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

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

Receive and delete messages from a queue

Download previously added messages by calling the receiveMessages method. The example code also deletes messages from the queue after they're received and processed. ここでの処理は、単にメッセージをコンソールに表示するだけです。

The app pauses for user input by calling System.console().readLine(); before it receives and deletes the messages. リソースが正しく作成されたことを Azure portal で確認してから、それらを削除してください。 明示的に削除されなかったメッセージは、最終的にキューに再表示され、別の機会に処理されます。

Add this code to the end of the main method:

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 メソッドを使用してキューを削除することにより、アプリによって作成されたリソースがクリーンアップされます。

Add this code to the end of the main method:

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");

コードを実行する

このアプリは、3 つのメッセージを作成して Azure のキューに追加します。 コードでは、キュー内のメッセージを一覧表示した後にそれらを取得して削除してから、最後にキューを削除します。

In your console window, navigate to your application directory, then build and run the application.

mvn compile

Then, build the package.

mvn package

Use the following mvn command to run the app.

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 portal でストレージ アカウントを確認してください。 キューにメッセージが存在することを確認します。

Enter キーを押してメッセージを受信し、削除します。 確認を求められたら、もう一度 Enter キーを押してキューを削除し、デモを終了します。

次のステップ

In this quickstart, you learned how to create a queue and add messages to it using Java code. その後、メッセージの表示、取得、削除を学びました。 最後に、メッセージ キューを削除する方法を説明しました。

For tutorials, samples, quick starts, and other documentation, visit: