.NET を使用して Azure Queue Storage とメッセージを作成および管理する
このユニットでは、.NET プロジェクトのコード スニペットを示して、Azure Queue Storage でキューを作成し、メッセージを管理する方法について説明します。
コード例は、次の NuGet パッケージに依存しています。
- .NET用 Azure.Core ライブラリ: このパッケージは、最新の .NET Azure SDK クライアント ライブラリ用の共有プリミティブ、抽象化、およびヘルパーを提供します。
- .NET用の Azure.Storage.Common クライアント ライブラリ: このパッケージは、他の Azure Storage クライアント ライブラリによって共有されるインフラストラクチャを提供します。
- .NET用 Azure.Storage.Queues クライアント ライブラリ: このパッケージを使用すると、クライアントからアクセスされたメッセージを格納するために Azure Queue Storage を操作できます。
- .NET用 System.Configuration.ConfigurationManager ライブラリ: このパッケージは、クライアント アプリケーションの構成ファイルへのアクセスを提供します。
Queue サービス クライアントを作成する
QueueClient
クラスを使用すると、Queue Storage に格納されているキューを取得できます。 サービス クライアントを作成する 1 つの方法を次に示します。
QueueClient queueClient = new QueueClient(connectionString, queueName);
キューを作成する
この例では、キューがまだ存在しない場合にキューを作成する方法を示します。
// Get the connection string from app settings
string connectionString = ConfigurationManager.AppSettings["StorageConnectionString"];
// Instantiate a QueueClient which will be used to create and manipulate the queue
QueueClient queueClient = new QueueClient(connectionString, queueName);
// Create the queue
queueClient.CreateIfNotExists();
キューにメッセージを挿入する
既存のキューにメッセージを挿入するには、SendMessage
メソッドを呼び出します。 メッセージには、文字列 (UTF-8 形式) またはバイト配列を指定できます。 次のコードは、キューを作成し (存在しない場合)、メッセージを挿入します。
// Get the connection string from app settings
string connectionString = ConfigurationManager.AppSettings["StorageConnectionString"];
// Instantiate a QueueClient which will be used to create and manipulate the queue
QueueClient queueClient = new QueueClient(connectionString, queueName);
// Create the queue if it doesn't already exist
queueClient.CreateIfNotExists();
if (queueClient.Exists())
{
// Send a message to the queue
queueClient.SendMessage(message);
}
次のメッセージを覗く
PeekMessages
メソッドを呼び出すことで、キューからメッセージを削除せずにキュー内のメッセージをピークできます。
maxMessages
パラメーターの値を渡さない場合、既定値は 1 つのメッセージをピークすることです。
// Get the connection string from app settings
string connectionString = ConfigurationManager.AppSettings["StorageConnectionString"];
// Instantiate a QueueClient which will be used to manipulate the queue
QueueClient queueClient = new QueueClient(connectionString, queueName);
if (queueClient.Exists())
{
// Peek at the next message
PeekedMessage[] peekedMessage = queueClient.PeekMessages();
}
キューに入ったメッセージの内容を変更する
キュー内のメッセージの内容をその場で変更できます。 メッセージが作業タスクを表している場合は、この機能を使用して作業タスクの状態を更新できます。 次のコードは、キュー メッセージを新しい内容で更新し、可視性のタイムアウトを設定してさらに 60 秒延長します。 これにより、メッセージに関連付けられている作業の状態が保存され、クライアントにメッセージの処理を続行する時間が与えられます。
// Get the connection string from app settings
string connectionString = ConfigurationManager.AppSettings["StorageConnectionString"];
// Instantiate a QueueClient which will be used to manipulate the queue
QueueClient queueClient = new QueueClient(connectionString, queueName);
if (queueClient.Exists())
{
// Get the message from the queue
QueueMessage[] message = queueClient.ReceiveMessages();
// Update the message contents
queueClient.UpdateMessage(message[0].MessageId,
message[0].PopReceipt,
"Updated contents",
TimeSpan.FromSeconds(60.0) // Make it invisible for another 60 seconds
);
}
次のメッセージをデキューする
2 つの手順でキューからメッセージをデキューします。
ReceiveMessages
を呼び出すと、キューに次のメッセージが表示されます。
ReceiveMessages
から返されたメッセージは、このキューからメッセージを読み取る他のコードからは見えなくなります。 既定では、このメッセージは 30 秒間非表示のままです。 キューからのメッセージの削除を完了するには、DeleteMessage
も呼び出す必要があります。 メッセージを削除するこの 2 段階のプロセスにより、ハードウェアまたはソフトウェアの障害が原因でコードでメッセージの処理が失敗した場合、コードの別のインスタンスが同じメッセージを取得して、もう一度やり直すことができます。 コードは、メッセージが処理された直後に DeleteMessage
呼び出します。
// Get the connection string from app settings
string connectionString = ConfigurationManager.AppSettings["StorageConnectionString"];
// Instantiate a QueueClient which will be used to manipulate the queue
QueueClient queueClient = new QueueClient(connectionString, queueName);
if (queueClient.Exists())
{
// Get the next message
QueueMessage[] retrievedMessage = queueClient.ReceiveMessages();
// Process (i.e. print) the message in less than 30 seconds
Console.WriteLine($"Dequeued message: '{retrievedMessage[0].Body}'");
// Delete the message
queueClient.DeleteMessage(retrievedMessage[0].MessageId, retrievedMessage[0].PopReceipt);
}
キューの長さを取得する
キュー内のメッセージ数の見積もりを取得できます。
GetProperties
メソッドは、メッセージ数を含むキューのプロパティを返します。
ApproximateMessagesCount
プロパティには、キュー内のメッセージの概数が含まれます。 この数は、キュー内の実際のメッセージ数よりも少なくありませんが、大きくなる可能性があります。
/// Instantiate a QueueClient which will be used to manipulate the queue
QueueClient queueClient = new QueueClient(connectionString, queueName);
if (queueClient.Exists())
{
QueueProperties properties = queueClient.GetProperties();
// Retrieve the cached approximate message count.
int cachedMessagesCount = properties.ApproximateMessagesCount;
// Display number of messages.
Console.WriteLine($"Number of messages in queue: {cachedMessagesCount}");
}
キューを削除する
キューとそのキューに含まれるすべてのメッセージを削除するには、queue オブジェクトで Delete
メソッドを呼び出します。
/// Get the connection string from app settings
string connectionString = ConfigurationManager.AppSettings["StorageConnectionString"];
// Instantiate a QueueClient which will be used to manipulate the queue
QueueClient queueClient = new QueueClient(connectionString, queueName);
if (queueClient.Exists())
{
// Delete the queue
queueClient.Delete();
}