Nuta
Dostęp do tej strony wymaga autoryzacji. Możesz spróbować się zalogować lub zmienić katalog.
Dostęp do tej strony wymaga autoryzacji. Możesz spróbować zmienić katalogi.
W tym artykule przedstawiono przykłady kodu, które używają wersji 11.x biblioteki klienta usługi Azure Queue Storage dla platformy .NET.
31 marca 2023 r. wycofaliśmy obsługę bibliotek zestawu Azure SDK, które nie są zgodne z bieżącymi wytycznymi dotyczącymi zestawu Azure SDK. Nowe biblioteki zestawu Azure SDK są regularnie aktualizowane w celu zapewnienia spójnych środowisk i poprawy stanu zabezpieczeń. Zaleca się przejście do nowych bibliotek zestawu Azure SDK w celu skorzystania z nowych funkcji i krytycznych aktualizacji zabezpieczeń.
Mimo że starsze biblioteki mogą być nadal używane poza 31 marca 2023 r., nie będą już otrzymywać oficjalnej pomocy technicznej i aktualizacji od firmy Microsoft. Aby uzyskać więcej informacji, zobacz ogłoszenie o wycofaniu pomocy technicznej.
Przykłady kodu korzystające z najnowszej wersji 12.x biblioteki klienta znajdują się w temacie Szybki start: biblioteka klienta usługi Azure Queue Storage dla platformy .NET.
Tworzenie klienta usługi Queue Storage
Klasa CloudQueueClient umożliwia pobieranie kolejek przechowywanych w usłudze Queue Storage. Oto jeden ze sposobów tworzenia klienta usługi:
// Retrieve storage account from connection string
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
CloudConfigurationManager.GetSetting("StorageConnectionString"));
// Create the queue client
CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();
Utwórz kolejkę
W tym przykładzie pokazano, jak utworzyć kolejkę:
// Retrieve storage account from connection string
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
CloudConfigurationManager.GetSetting("StorageConnectionString"));
// Create the queue client
CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();
// Retrieve a reference to a queue
CloudQueue queue = queueClient.GetQueueReference("myqueue");
// Create the queue if it doesn't already exist
queue.CreateIfNotExists();
Wstaw komunikat do kolejki
Aby wstawić komunikat do istniejącej kolejki, najpierw utwórz nowy CloudQueueMessage element. Następnie wywołaj metodę AddMessage . Element CloudQueueMessage można utworzyć na podstawie ciągu (w formacie UTF-8) lub tablicy bajtów. Poniższy przykład kodu tworzy kolejkę (jeśli jeszcze nie istnieje) i wstawia komunikat Hello, World:
// Retrieve storage account from connection string
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
CloudConfigurationManager.GetSetting("StorageConnectionString"));
// Create the queue client
CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();
// Retrieve a reference to a queue
CloudQueue queue = queueClient.GetQueueReference("myqueue");
// Create the queue if it doesn't already exist
queue.CreateIfNotExists();
// Create a message and add it to the queue
CloudQueueMessage message = new CloudQueueMessage("Hello, World");
queue.AddMessage(message);
Rzut oka na następny komunikat
Możesz zajrzeć do wiadomości z przodu kolejki bez jej usuwania z kolejki, wywołując metodę PeekMessage.
// Retrieve storage account from connection string
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
CloudConfigurationManager.GetSetting("StorageConnectionString"));
// Create the queue client
CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();
// Retrieve a reference to a queue
CloudQueue queue = queueClient.GetQueueReference("myqueue");
// Peek at the next message
CloudQueueMessage peekedMessage = queue.PeekMessage();
// Display message.
Console.WriteLine(peekedMessage.AsString);
Zmiana zawartości komunikatu w kolejce
// Retrieve storage account from connection string.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
CloudConfigurationManager.GetSetting("StorageConnectionString"));
// Create the queue client.
CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();
// Retrieve a reference to a queue.
CloudQueue queue = queueClient.GetQueueReference("myqueue");
// Get the message from the queue and update the message contents.
CloudQueueMessage message = queue.GetMessage();
message.SetMessageContent2("Updated contents.", false);
queue.UpdateMessage(message,
TimeSpan.FromSeconds(60.0), // Make it invisible for another 60 seconds.
MessageUpdateFields.Content | MessageUpdateFields.Visibility);
Usuń następną wiadomość z kolejki
Twój kod usuwa komunikat z kolejki w dwóch krokach. Po wywołaniu GetMessage, zostanie wyświetlony następny komunikat w kolejce. Komunikat zwrócony z GetMessage staje się niewidoczny dla innych programów odczytujących komunikaty z tej kolejki. Domyślnie komunikat pozostanie niewidoczny przez 30 sekund. Aby zakończyć usuwanie komunikatu z kolejki, należy również wywołać metodę DeleteMessage. Ten dwuetapowy proces usuwania komunikatów gwarantuje, że jeśli kod nie będzie w stanie przetworzyć komunikatu z powodu awarii sprzętu lub oprogramowania, inne wystąpienie kodu będzie w stanie uzyskać ten sam komunikat i ponowić próbę. Funkcja DeleteMessage jest wywoływana bezpośrednio po przetworzeniu wiadomości.
// Retrieve storage account from connection string
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
CloudConfigurationManager.GetSetting("StorageConnectionString"));
// Create the queue client
CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();
// Retrieve a reference to a queue
CloudQueue queue = queueClient.GetQueueReference("myqueue");
// Get the next message
CloudQueueMessage retrievedMessage = queue.GetMessage();
//Process the message in less than 30 seconds, and then delete the message
queue.DeleteMessage(retrievedMessage);
Używanie wzorca async-await z typowymi interfejsami API usługi Queue Storage
// Create the queue if it doesn't already exist
if(await queue.CreateIfNotExistsAsync())
{
Console.WriteLine("Queue '{0}' Created", queue.Name);
}
else
{
Console.WriteLine("Queue '{0}' Exists", queue.Name);
}
// Create a message to put in the queue
CloudQueueMessage cloudQueueMessage = new CloudQueueMessage("My message");
// Async enqueue the message
await queue.AddMessageAsync(cloudQueueMessage);
Console.WriteLine("Message added");
// Async dequeue the message
CloudQueueMessage retrievedMessage = await queue.GetMessageAsync();
Console.WriteLine("Retrieved message with content '{0}'", retrievedMessage.AsString);
// Async delete the message
await queue.DeleteMessageAsync(retrievedMessage);
Console.WriteLine("Deleted message");
Użyj dodatkowych opcji odkolejkowywania komunikatów
W poniższym przykładzie kodu użyto metody GetMessages, aby pobrać 20 wiadomości w jednym wywołaniu. Następnie przetwarza każdy komunikat przy użyciu foreach pętli. Ustawia również limitu czasu niewidoczności na pięć minut dla każdego komunikatu. Limit czasowy rozpoczyna się dla wszystkich wiadomości w tym samym czasie, więc po upływie pięciu minut od wywołania metody GetMessages, wszystkie wiadomości, które nie zostały usunięte, staną się ponownie widoczne.
// Retrieve storage account from connection string.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
CloudConfigurationManager.GetSetting("StorageConnectionString"));
// Create the queue client.
CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();
// Retrieve a reference to a queue.
CloudQueue queue = queueClient.GetQueueReference("myqueue");
foreach (CloudQueueMessage message in queue.GetMessages(20, TimeSpan.FromMinutes(5)))
{
// Process all messages in less than 5 minutes, deleting each message after processing.
queue.DeleteMessage(message);
}
Pobierz długość kolejki
Możesz oszacować ilość wiadomości w kolejce. Metoda FetchAttributes zwraca atrybuty kolejki, w tym liczbę komunikatów. Właściwość ApproximateMessageCount zwraca ostatnią wartość pobraną przez metodę FetchAttributes bez wywoływania usługi Queue Storage.
// Retrieve storage account from connection string.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
CloudConfigurationManager.GetSetting("StorageConnectionString"));
// Create the queue client.
CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();
// Retrieve a reference to a queue.
CloudQueue queue = queueClient.GetQueueReference("myqueue");
// Fetch the queue attributes.
queue.FetchAttributes();
// Retrieve the cached approximate message count.
int cachedMessageCount = queue.ApproximateMessageCount;
// Display number of messages.
Console.WriteLine("Number of messages in queue: " + cachedMessageCount);
Usuń kolejkę
Aby usunąć kolejkę i wszystkie zawarte w niej komunikaty, wywołaj metodę Delete w obiekcie kolejki.
// Retrieve storage account from connection string.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
CloudConfigurationManager.GetSetting("StorageConnectionString"));
// Create the queue client.
CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();
// Retrieve a reference to a queue.
CloudQueue queue = queueClient.GetQueueReference("myqueue");
// Delete the queue.
queue.Delete();
Praca z kolejkami
Powiązany artykuł: Praca z kolejkami usługi Azure Queue Storage na platformie .NET
W katalogu projektu dodaj następujące pakiety przy użyciu dotnet add package polecenia :
dotnet add package Microsoft.Azure.Storage.Common
dotnet add package Microsoft.Azure.Storage.Queue
Pełny przykład kodu:
using System;
using System.Threading.Tasks;
using Microsoft.Azure.Storage;
using Microsoft.Azure.Storage.Queue;
namespace QueueApp
{
class Program
{
static async Task Main(string[] args)
{
string connectionString = Environment.GetEnvironmentVariable("AZURE_STORAGE_CONNECTION_STRING");
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);
CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();
CloudQueue queue = queueClient.GetQueueReference("mystoragequeue");
if (args.Length > 0)
{
string value = String.Join(" ", args);
await InsertMessageAsync(queue, value);
Console.WriteLine($"Sent: {value}");
}
else
{
string value = await RetrieveNextMessageAsync(queue);
Console.WriteLine($"Received: {value}");
}
Console.Write("Press Enter...");
Console.ReadLine();
}
static async Task InsertMessageAsync(CloudQueue theQueue, string newMessage)
{
if (await theQueue.CreateIfNotExistsAsync())
{
Console.WriteLine("The queue was created.");
}
CloudQueueMessage message = new CloudQueueMessage(newMessage);
await theQueue.AddMessageAsync(message);
}
static async Task<string> RetrieveNextMessageAsync(CloudQueue theQueue)
{
bool exists = await theQueue.ExistsAsync();
if (exists)
{
CloudQueueMessage retrievedMessage = await theQueue.GetMessageAsync();
if (retrievedMessage != null)
{
string theMessage = retrievedMessage.AsString;
await theQueue.DeleteMessageAsync(retrievedMessage);
return theMessage;
}
else
{
Console.Write("The queue is empty. Attempt to delete it? (Y/N) ");
string response = Console.ReadLine();
if (response.ToUpper() == "Y")
{
await theQueue.DeleteIfExistsAsync();
return "The queue was deleted.";
}
else
{
return "The queue was not deleted.";
}
}
}
else
{
return "The queue does not exist. Add a message to the command line to create the queue and store the message.";
}
}
}
}