概要
このガイドでは、Azure Queue Storage サービスを使用して一般的なシナリオをコーディングする方法について説明します。 サンプルは Java で記述され、 Azure Storage SDK for Java を使用します。 シナリオには、キュー メッセージの挿入、確認、取得、削除が含まれています。 キュー を作成 および 削除するための コードについても説明します。 キューの詳細については、「 次のステップ 」セクションを参照してください。
Queue Storage とは
Azure Queue Storage は、HTTP または HTTPS を使用して認証された呼び出しを介して世界中のどこからでもアクセスできる多数のメッセージを格納するためのサービスです。 1 つのキュー メッセージのサイズは最大 64 KB で、キューにはストレージ アカウントの合計容量制限まで、数百万のメッセージを含めることができます。 キュー ストレージは、非同期的に処理する作業のバックログを作成するためによく使用されます。
キューサービスの概念
Azure Queue サービスには、次のコンポーネントが含まれています。
Azure Queue サービス コンポーネント
#B0 ストレージ アカウント: #C1 Azure Storage へのすべてのアクセスは、ストレージ アカウントを介して行われます。 ストレージ アカウントの詳細については、「ストレージ アカウントの概要」を参照してください。
キュー: キューは、メッセージのセットを格納します。 すべてのメッセージはキューに 格納されている必要があります。 キュー名は小文字で入力する必要があります。 キューの名前付け規則については、「 Naming Queues and Metadata (キューとメタデータの名前付け規則)」を参照してください。
メッセージ: 形式を問わず、メッセージのサイズは最大で 64 KB です。 メッセージがキューに残ることができる最大時間は 7 日間です。 バージョン 2017-07-29 以降では、最大有効期間を任意の正の数にすることができます。また、-1 は、メッセージが期限切れにならないことを示します。 このパラメーターを省略すると、既定の有効期間は 7 日になります。
URL 形式: キューは、次の URL 形式を使用してアドレス指定できます: http://.queue.core.windows.net/
<storage account>次の URL は、図内のキューをアドレス指定します。
http://myaccount.queue.core.windows.net/incoming-orders
Azure Storage アカウントを作成する
最初の Azure ストレージ アカウントを作成する最も簡単な方法は、Azure portalを使用することです。 詳細については、「 ストレージ アカウントの作成」を参照してください。
Azure PowerShell 、Azure CLI 、または .NET 用Azure Storage Resource Provider使用して、Azure ストレージ アカウントを作成することもできます。
現時点で Azure でストレージ アカウントを作成しない場合は、Azurite ストレージ エミュレーターを使用して、ローカル環境でコードを実行してテストすることもできます。 詳細については、「ローカルの Azure Storage 開発に Azurite エミュレーターを使用する」を参照してください。
Java アプリケーションの作成
まず、開発システムが 、Java 用 Azure Queue Storage クライアント ライブラリ v12 に記載されている前提条件を満たしていることを確認します。
queues-how-to-v12という名前の Java アプリケーションを作成するには:
コンソール ウィンドウ (cmd、PowerShell、Bash など) で Maven を使用して、
queues-how-to-v12という名前の新しいコンソール アプリを作成します。 次のmvnコマンドを入力して、"hello world" Java プロジェクトを作成します。mvn archetype:generate \ --define interactiveMode=n \ --define groupId=com.queues.howto \ --define artifactId=queues-howto-v12 \ --define archetypeArtifactId=maven-archetype-quickstart \ --define archetypeVersion=1.4mvn archetype:generate ` --define interactiveMode=n ` --define groupId=com.queues.howto ` --define artifactId=queues-howto-v12 ` --define archetypeArtifactId=maven-archetype-quickstart ` --define archetypeVersion=1.4プロジェクトを生成した際の出力は次のようになります。
[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.howto [INFO] Parameter: artifactId, Value: queues-howto-v12 [INFO] Parameter: version, Value: 1.0-SNAPSHOT [INFO] Parameter: package, Value: com.queues.howto [INFO] Parameter: packageInPathFormat, Value: com/queues/howto [INFO] Parameter: version, Value: 1.0-SNAPSHOT [INFO] Parameter: package, Value: com.queues.howto [INFO] Parameter: groupId, Value: com.queues.howto [INFO] Parameter: artifactId, Value: queues-howto-v12 [INFO] Project created from Archetype in dir: C:\queues\queues-howto-v12 [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 6.775 s [INFO] Finished at: 2020-08-17T15:27:31-07:00 [INFO] ------------------------------------------------------------------------新しく作成した
queues-howto-v12ディレクトリに切り替えます。cd queues-howto-v12
パッケージをインストールする
テキストエディタでpom.xmlファイルを開いてください。 依存関係のグループに、次の dependency 要素を追加します。
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-storage-queue</artifactId>
<version>12.6.0</version>
</dependency>
Queue Storage にアクセスするようにアプリケーションを構成する
Azure Storage API を使用してキューにアクセスする Java ファイルの先頭に、次の import ステートメントを追加します。
// Include the following imports to use queue APIs
import com.azure.core.util.*;
import com.azure.storage.queue.*;
import com.azure.storage.queue.models.*;
Azure Storage 接続文字列の設定
Azure Storage クライアントは、データ管理サービスにアクセスするためにストレージ接続文字列を使用します。
Azure portal に一覧表示されているストレージ アカウントの名前とプライマリ アクセス キーを取得します。 接続文字列の AccountName と AccountKey の値として使用します。 この例では、接続文字列を保持する静的フィールドを宣言する方法を示しています。
// Define the connection-string with your values
final String connectStr =
"DefaultEndpointsProtocol=https;" +
"AccountName=your_storage_account;" +
"AccountKey=your_storage_account_key";
次のサンプルでは、ストレージ接続文字列を含む String オブジェクトがあることを前提としています。
方法: キューを作成する
QueueClient オブジェクトには、キューと対話するための操作が含まれています。 次のコードでは、 QueueClient オブジェクトを作成します。
QueueClient オブジェクトを使用して、使用するキューを作成します。
public static String createQueue(String connectStr)
{
try
{
// Create a unique name for the queue
String queueName = "queue-" + java.util.UUID.randomUUID();
System.out.println("Creating queue: " + queueName);
// Instantiate a QueueClient which will be
// used to create and manipulate the queue
QueueClient queue = new QueueClientBuilder()
.connectionString(connectStr)
.queueName(queueName)
.buildClient();
// Create the queue
queue.create();
return queue.getQueueName();
}
catch (QueueStorageException e)
{
// Output the exception message and stack trace
System.out.println("Error code: " + e.getErrorCode() + "Message: " + e.getMessage());
return null;
}
}
方法: キューにメッセージを追加する
既存のキューにメッセージを挿入するには、sendMessage メソッドを呼び出します。 メッセージには、文字列 (UTF-8 形式) またはバイト配列を指定できます。 キューに文字列メッセージを送信するコードを次に示します。
public static void addQueueMessage
(String connectStr, String queueName, String messageText)
{
try
{
// Instantiate a QueueClient which will be
// used to create and manipulate the queue
QueueClient queueClient = new QueueClientBuilder()
.connectionString(connectStr)
.queueName(queueName)
.buildClient();
System.out.println("Adding message to the queue: " + messageText);
// Add a message to the queue
queueClient.sendMessage(messageText);
}
catch (QueueStorageException e)
{
// Output the exception message and stack trace
System.out.println(e.getMessage());
e.printStackTrace();
}
}
方法: 次のメッセージを確認する
peekMessageを呼び出すことで、キューからメッセージを削除せずに、キューの前面にあるメッセージをピークできます。
public static void peekQueueMessage
(String connectStr, String queueName)
{
try
{
// Instantiate a QueueClient which will be
// used to create and manipulate the queue
QueueClient queueClient = new QueueClientBuilder()
.connectionString(connectStr)
.queueName(queueName)
.buildClient();
// Peek at the first message
PeekedMessageItem peekedMessageItem = queueClient.peekMessage();
System.out.println("Peeked message: " + peekedMessageItem.getMessageText());
}
catch (QueueStorageException e)
{
// Output the exception message and stack trace
System.out.println(e.getMessage());
e.printStackTrace();
}
}
方法: キューに登録されたメッセージの内容を変更する
キュー内のメッセージの内容をその場で変更できます。 メッセージが作業タスクを表している場合は、この機能を使用して状態を更新できます。 次のコードでは、キュー メッセージを新しい内容で更新し、可視性のタイムアウトを設定してさらに 30 秒延長します。 可視性タイムアウトを延長すると、クライアントはメッセージの処理を続行するためにさらに 30 秒が与えられます。 再試行回数を保持することもできます。 メッセージが n 回以上再試行された場合は、メッセージを削除します。 このシナリオでは、処理されるたびにアプリケーション エラーをトリガーするメッセージから保護します。
次のコード サンプルでは、メッセージのキューを検索し、検索文字列に一致する最初のメッセージ コンテンツを検索し、メッセージの内容を変更して終了します。
public static void updateQueueMessage
(String connectStr, String queueName,
String searchString, String updatedContents)
{
try
{
// Instantiate a QueueClient which will be
// used to create and manipulate the queue
QueueClient queueClient = new QueueClientBuilder()
.connectionString(connectStr)
.queueName(queueName)
.buildClient();
// The maximum number of messages to retrieve is 32
final int MAX_MESSAGES = 32;
// Iterate through the queue messages
for (QueueMessageItem message : queueClient.receiveMessages(MAX_MESSAGES))
{
// Check for a specific string
if (message.getMessageText().equals(searchString))
{
// Update the message to be visible in 30 seconds
queueClient.updateMessage(message.getMessageId(),
message.getPopReceipt(),
updatedContents,
Duration.ofSeconds(30));
System.out.println(
String.format("Found message: \'%s\' and updated it to \'%s\'",
searchString,
updatedContents)
);
break;
}
}
}
catch (QueueStorageException e)
{
// Output the exception message and stack trace
System.out.println(e.getMessage());
e.printStackTrace();
}
}
次のコード サンプルでは、キュー内の最初に表示されるメッセージのみを更新します。
public static void updateFirstQueueMessage
(String connectStr, String queueName, String updatedContents)
{
try
{
// Instantiate a QueueClient which will be
// used to create and manipulate the queue
QueueClient queueClient = new QueueClientBuilder()
.connectionString(connectStr)
.queueName(queueName)
.buildClient();
// Get the first queue message
QueueMessageItem message = queueClient.receiveMessage();
// Check for a specific string
if (null != message)
{
// Update the message to be visible in 30 seconds
UpdateMessageResult result = queueClient.updateMessage(message.getMessageId(),
message.getPopReceipt(),
updatedContents,
Duration.ofSeconds(30));
System.out.println("Updated the first message with the receipt: " +
result.getPopReceipt());
}
}
catch (QueueStorageException e)
{
// Output the exception message and stack trace
System.out.println(e.getMessage());
e.printStackTrace();
}
}
方法: キューの長さを取得する
キュー内のメッセージ数の見積もりを取得できます。
getProperties メソッドは、キュー内に現在存在するメッセージの数を含む、いくつかの値を返します。 ja-JP: 件数はあくまで概算であり、リクエスト後にはメッセージが追加されたり削除されたりする可能性があります。
getApproximateMessageCount メソッドは、Queue Storage を呼び出すことなく、getProperties の呼び出しによって取得された最後の値を返します。
public static void getQueueLength(String connectStr, String queueName)
{
try
{
// Instantiate a QueueClient which will be
// used to create and manipulate the queue
QueueClient queueClient = new QueueClientBuilder()
.connectionString(connectStr)
.queueName(queueName)
.buildClient();
QueueProperties properties = queueClient.getProperties();
long messageCount = properties.getApproximateMessagesCount();
System.out.println(String.format("Queue length: %d", messageCount));
}
catch (QueueStorageException e)
{
// Output the exception message and stack trace
System.out.println(e.getMessage());
e.printStackTrace();
}
}
方法: 次のメッセージをデキューする
コードは、キューからのメッセージを 2 つの手順でデキューします。
receiveMessageを呼び出すと、キューに次のメッセージが表示されます。
receiveMessage から返されたメッセージは、このキューからメッセージを読み取る他のコードから参照できなくなります。 既定では、このメッセージは 30 秒間非表示のままです。 キューからのメッセージの削除を完了するには、deleteMessageも呼び出す必要があります。 コードでメッセージの処理に失敗した場合、この 2 段階のプロセスにより、同じメッセージを取得してもう一度やり直すことができます。 コードは、メッセージが処理された直後に deleteMessage 呼び出します。
public static void dequeueMessage(String connectStr, String queueName)
{
try
{
// Instantiate a QueueClient which will be
// used to create and manipulate the queue
QueueClient queueClient = new QueueClientBuilder()
.connectionString(connectStr)
.queueName(queueName)
.buildClient();
// Get the first queue message
QueueMessageItem message = queueClient.receiveMessage();
// Check for a specific string
if (null != message)
{
System.out.println("Dequeing message: " + message.getMessageText());
// Delete the message
queueClient.deleteMessage(message.getMessageId(), message.getPopReceipt());
}
else
{
System.out.println("No visible messages in queue");
}
}
catch (QueueStorageException e)
{
// Output the exception message and stack trace
System.out.println(e.getMessage());
e.printStackTrace();
}
}
メッセージのデキュー用の追加オプション
キューからのメッセージ取得をカスタマイズするには、2 つの方法があります。 まず、メッセージのバッチを取得します (最大 32)。 次に、非表示タイムアウトを長くまたは短く設定して、コードで各メッセージを完全に処理する時間を増減します。
次のコード例では、 receiveMessages メソッドを使用して、1 回の呼び出しで 20 個のメッセージを取得します。 その後、for ループを使用して、各メッセージを処理します。 また、各メッセージの非表示タイムアウトを 5 分 (300 秒) に設定します。 タイムアウトはすべてのメッセージに対して同時に開始されます。
receiveMessagesの呼び出しから 5 分が経過すると、削除されていないメッセージが再び表示されます。
public static void dequeueMessages(String connectStr, String queueName)
{
try
{
// Instantiate a QueueClient which will be
// used to create and manipulate the queue
QueueClient queueClient = new QueueClientBuilder()
.connectionString(connectStr)
.queueName(queueName)
.buildClient();
// The maximum number of messages to retrieve is 20
final int MAX_MESSAGES = 20;
// Retrieve 20 messages from the queue with a
// visibility timeout of 300 seconds (5 minutes)
for (QueueMessageItem message : queueClient.receiveMessages(MAX_MESSAGES,
Duration.ofSeconds(300), Duration.ofSeconds(1), new Context("key1", "value1")))
{
// Do processing for all messages in less than 5 minutes,
// deleting each message after processing.
System.out.println("Dequeing message: " + message.getMessageText());
queueClient.deleteMessage(message.getMessageId(), message.getPopReceipt());
}
}
catch (QueueStorageException e)
{
// Output the exception message and stack trace
System.out.println(e.getMessage());
e.printStackTrace();
}
}
方法: キューを一覧表示する
現在のキューの一覧を取得するには、 QueueServiceClient.listQueues() メソッドを呼び出します。このメソッドは、 QueueItem オブジェクトのコレクションを返します。
public static void listQueues(String connectStr)
{
try
{
// Instantiate a QueueServiceClient which will be
// used to list the queues
QueueServiceClient queueServiceClient = new QueueServiceClientBuilder()
.connectionString(connectStr)
.buildClient();
// Loop through the collection of queues.
for (QueueItem queue : queueServiceClient.listQueues())
{
// Output each queue name.
System.out.println(queue.getName());
}
}
catch (QueueStorageException e)
{
// Output the exception message and stack trace
System.out.println(e.getMessage());
e.printStackTrace();
}
}
方法: キューを削除する
キューとそのキューに含まれるすべてのメッセージを削除するには、QueueClient オブジェクトで delete メソッドを呼び出します。
public static void deleteMessageQueue(String connectStr, String queueName)
{
try
{
// Instantiate a QueueClient which will be
// used to create and manipulate the queue
QueueClient queueClient = new QueueClientBuilder()
.connectionString(connectStr)
.queueName(queueName)
.buildClient();
System.out.println("Deleting queue: " + queueClient.getQueueName());
// Delete the queue
queueClient.delete();
}
catch (QueueStorageException e)
{
// Output the exception message and stack trace
System.out.println(e.getMessage());
e.printStackTrace();
}
}
ヒント
Azure Storage コード サンプル レポジトリを参照してください
ダウンロードして実行できる、使いやすいエンド ツー エンドの Azure Storage コード サンプルについては、Azure Storage のサンプルの一覧を確認してください。
次のステップ
Queue Storage の基本を学習したので、これらのリンクに従って、より複雑なストレージ タスクについて学習します。
- Azure Storage SDK for Java
- Azure Storage クライアント SDK リファレンス
- Azure Storage サービス REST API
- Azure Storage チームのブログ
非推奨のJavaバージョン8のSDKを使用した関連コードサンプルについては、Javaバージョン8を使用したコードサンプルをご覧ください。