创建 Amazon SQS 队列 - Amazon SDK for .NET
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

创建 Amazon SQS 队列

此示例向您展示如何使用 Amazon SDK for .NET 创建 Amazon SQS 队列。如果您不提供死信队列的 ARN,则应用程序会创建一个死信队列。然后,它会创建一个标准消息队列,其中包括死信队列(您提供的队列或创建的队列)。

如果您不提供任何命令行参数,则应用程序仅显示有关所有现有队列的信息。

以下各节提供了此示例的片段。此后显示了该示例的完整代码,并且可以按原样构建和运行。

显示现有队列

以下代码片段显示了 SQS 客户端区域中现有队列的列表以及每个队列的属性。

本主题末尾的示例显示了此片段的使用情况。

// // Method to show a list of the existing queues private static async Task ShowQueues(IAmazonSQS sqsClient) { ListQueuesResponse responseList = await sqsClient.ListQueuesAsync(""); Console.WriteLine(); foreach(string qUrl in responseList.QueueUrls) { // Get and show all attributes. Could also get a subset. await ShowAllAttributes(sqsClient, qUrl); } } // // Method to show all attributes of a queue private static async Task ShowAllAttributes(IAmazonSQS sqsClient, string qUrl) { var attributes = new List<string>{ QueueAttributeName.All }; GetQueueAttributesResponse responseGetAtt = await sqsClient.GetQueueAttributesAsync(qUrl, attributes); Console.WriteLine($"Queue: {qUrl}"); foreach(var att in responseGetAtt.Attributes) Console.WriteLine($"\t{att.Key}: {att.Value}"); }

创建队列

以下代码片段创建队列。该片段包括死信队列的使用,但队列不一定需要死信队列。

本主题末尾的示例显示了此片段的使用情况。

// // Method to create a queue. Returns the queue URL. private static async Task<string> CreateQueue( IAmazonSQS sqsClient, string qName, string deadLetterQueueUrl=null, string maxReceiveCount=null, string receiveWaitTime=null) { var attrs = new Dictionary<string, string>(); // If a dead-letter queue is given, create a message queue if(!string.IsNullOrEmpty(deadLetterQueueUrl)) { attrs.Add(QueueAttributeName.ReceiveMessageWaitTimeSeconds, receiveWaitTime); attrs.Add(QueueAttributeName.RedrivePolicy, $"{{\"deadLetterTargetArn\":\"{await GetQueueArn(sqsClient, deadLetterQueueUrl)}\"," + $"\"maxReceiveCount\":\"{maxReceiveCount}\"}}"); // Add other attributes for the message queue such as VisibilityTimeout } // If no dead-letter queue is given, create one of those instead //else //{ // // Add attributes for the dead-letter queue as needed // attrs.Add(); //} // Create the queue CreateQueueResponse responseCreate = await sqsClient.CreateQueueAsync( new CreateQueueRequest{QueueName = qName, Attributes = attrs}); return responseCreate.QueueUrl; }

获取队列的 ARN

以下代码片段获取由给定队列 URL 标识的队列的 ARN。

本主题末尾的示例显示了此片段的使用情况。

// // Method to get the ARN of a queue private static async Task<string> GetQueueArn(IAmazonSQS sqsClient, string qUrl) { GetQueueAttributesResponse responseGetAtt = await sqsClient.GetQueueAttributesAsync( qUrl, new List<string>{QueueAttributeName.QueueArn}); return responseGetAtt.QueueARN; }

完整代码

本部分显示了本示例的相关参考和完整代码。

using System; using System.Threading.Tasks; using System.Collections.Generic; using Amazon.SQS; using Amazon.SQS.Model; namespace SQSCreateQueue { // = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = // Class to create a queue class Program { private const string MaxReceiveCount = "10"; private const string ReceiveMessageWaitTime = "2"; private const int MaxArgs = 3; static async Task Main(string[] args) { // Parse the command line and show help if necessary var parsedArgs = CommandLine.Parse(args); if(parsedArgs.Count > MaxArgs) CommandLine.ErrorExit( "\nToo many command-line arguments.\nRun the command with no arguments to see help."); // Create the Amazon SQS client var sqsClient = new AmazonSQSClient(); // In the case of no command-line arguments, just show help and the existing queues if(parsedArgs.Count == 0) { PrintHelp(); Console.WriteLine("\nNo arguments specified."); Console.Write("Do you want to see a list of the existing queues? ((y) or n): "); string response = Console.ReadLine(); if((string.IsNullOrEmpty(response)) || (response.ToLower() == "y")) await ShowQueues(sqsClient); return; } // Get the application arguments from the parsed list string queueName = CommandLine.GetArgument(parsedArgs, null, "-q", "--queue-name"); string deadLetterQueueUrl = CommandLine.GetArgument(parsedArgs, null, "-d", "--dead-letter-queue"); string maxReceiveCount = CommandLine.GetArgument(parsedArgs, MaxReceiveCount, "-m", "--max-receive-count"); string receiveWaitTime = CommandLine.GetArgument(parsedArgs, ReceiveMessageWaitTime, "-w", "--wait-time"); if(string.IsNullOrEmpty(queueName)) CommandLine.ErrorExit( "\nYou must supply a queue name.\nRun the command with no arguments to see help."); // If a dead-letter queue wasn't given, create one if(string.IsNullOrEmpty(deadLetterQueueUrl)) { Console.WriteLine("\nNo dead-letter queue was specified. Creating one..."); deadLetterQueueUrl = await CreateQueue(sqsClient, queueName + "__dlq"); Console.WriteLine($"Your new dead-letter queue:"); await ShowAllAttributes(sqsClient, deadLetterQueueUrl); } // Create the message queue string messageQueueUrl = await CreateQueue( sqsClient, queueName, deadLetterQueueUrl, maxReceiveCount, receiveWaitTime); Console.WriteLine($"Your new message queue:"); await ShowAllAttributes(sqsClient, messageQueueUrl); } // // Method to show a list of the existing queues private static async Task ShowQueues(IAmazonSQS sqsClient) { ListQueuesResponse responseList = await sqsClient.ListQueuesAsync(""); Console.WriteLine(); foreach(string qUrl in responseList.QueueUrls) { // Get and show all attributes. Could also get a subset. await ShowAllAttributes(sqsClient, qUrl); } } // // Method to create a queue. Returns the queue URL. private static async Task<string> CreateQueue( IAmazonSQS sqsClient, string qName, string deadLetterQueueUrl=null, string maxReceiveCount=null, string receiveWaitTime=null) { var attrs = new Dictionary<string, string>(); // If a dead-letter queue is given, create a message queue if(!string.IsNullOrEmpty(deadLetterQueueUrl)) { attrs.Add(QueueAttributeName.ReceiveMessageWaitTimeSeconds, receiveWaitTime); attrs.Add(QueueAttributeName.RedrivePolicy, $"{{\"deadLetterTargetArn\":\"{await GetQueueArn(sqsClient, deadLetterQueueUrl)}\"," + $"\"maxReceiveCount\":\"{maxReceiveCount}\"}}"); // Add other attributes for the message queue such as VisibilityTimeout } // If no dead-letter queue is given, create one of those instead //else //{ // // Add attributes for the dead-letter queue as needed // attrs.Add(); //} // Create the queue CreateQueueResponse responseCreate = await sqsClient.CreateQueueAsync( new CreateQueueRequest{QueueName = qName, Attributes = attrs}); return responseCreate.QueueUrl; } // // Method to get the ARN of a queue private static async Task<string> GetQueueArn(IAmazonSQS sqsClient, string qUrl) { GetQueueAttributesResponse responseGetAtt = await sqsClient.GetQueueAttributesAsync( qUrl, new List<string>{QueueAttributeName.QueueArn}); return responseGetAtt.QueueARN; } // // Method to show all attributes of a queue private static async Task ShowAllAttributes(IAmazonSQS sqsClient, string qUrl) { var attributes = new List<string>{ QueueAttributeName.All }; GetQueueAttributesResponse responseGetAtt = await sqsClient.GetQueueAttributesAsync(qUrl, attributes); Console.WriteLine($"Queue: {qUrl}"); foreach(var att in responseGetAtt.Attributes) Console.WriteLine($"\t{att.Key}: {att.Value}"); } // // Command-line help private static void PrintHelp() { Console.WriteLine( "\nUsage: SQSCreateQueue -q <queue-name> [-d <dead-letter-queue>]" + " [-m <max-receive-count>] [-w <wait-time>]" + "\n -q, --queue-name: The name of the queue you want to create." + "\n -d, --dead-letter-queue: The URL of an existing queue to be used as the dead-letter queue."+ "\n If this argument isn't supplied, a new dead-letter queue will be created." + "\n -m, --max-receive-count: The value for maxReceiveCount in the RedrivePolicy of the queue." + $"\n Default is {MaxReceiveCount}." + "\n -w, --wait-time: The value for ReceiveMessageWaitTimeSeconds of the queue for long polling." + $"\n Default is {ReceiveMessageWaitTime}."); } } // = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = // Class that represents a command line on the console or terminal. // (This is the same for all examples. When you have seen it once, you can ignore it.) static class CommandLine { // // Method to parse a command line of the form: "--key value" or "-k value". // // Parameters: // - args: The command-line arguments passed into the application by the system. // // Returns: // A Dictionary with string Keys and Values. // // If a key is found without a matching value, Dictionary.Value is set to the key // (including the dashes). // If a value is found without a matching key, Dictionary.Key is set to "--NoKeyN", // where "N" represents sequential numbers. public static Dictionary<string,string> Parse(string[] args) { var parsedArgs = new Dictionary<string,string>(); int i = 0, n = 0; while(i < args.Length) { // If the first argument in this iteration starts with a dash it's an option. if(args[i].StartsWith("-")) { var key = args[i++]; var value = key; // Check to see if there's a value that goes with this option? if((i < args.Length) && (!args[i].StartsWith("-"))) value = args[i++]; parsedArgs.Add(key, value); } // If the first argument in this iteration doesn't start with a dash, it's a value else { parsedArgs.Add("--NoKey" + n.ToString(), args[i++]); n++; } } return parsedArgs; } // // Method to get an argument from the parsed command-line arguments // // Parameters: // - parsedArgs: The Dictionary object returned from the Parse() method (shown above). // - defaultValue: The default string to return if the specified key isn't in parsedArgs. // - keys: An array of keys to look for in parsedArgs. public static string GetArgument( Dictionary<string,string> parsedArgs, string defaultReturn, params string[] keys) { string retval = null; foreach(var key in keys) if(parsedArgs.TryGetValue(key, out retval)) break; return retval ?? defaultReturn; } // // Method to exit the application with an error. public static void ErrorExit(string msg, int code=1) { Console.WriteLine("\nError"); Console.WriteLine(msg); Environment.Exit(code); } } }

其他注意事项

  • 您的队列名称必须由字母数字字符、连字符和下划线组成。

  • 队列名称和队列 URL 区分大小写

  • 如果您需要队列 URL 但只有队列名称,请使用其中一种 AmazonSQSClient.GetQueueUrlAsync 方法。

  • 此示例指定对您创建的队列中的所有消息进行长轮询。可使用 ReceiveMessageWaitTimeSeconds 属性执行此操作。

    您还可以在调用 AmazonSqsClient 类的 ReceiveMessageAsync 方法期间指定长轮询。有关更多信息,请参阅接收 Amazon SQS 消息

    有关短轮询与长轮询的信息,请参阅《Amazon Simple Queue Service 开发人员指南》中的短轮询与长轮询

  • 其它(源)队列可将未成功处理的消息转到死信队列。有关更多信息,请参阅《Amazon Simple Queue Service 开发人员指南》中的 Amazon SQS 死信队列