CreateQueue 搭配 AWS SDK或 使用 CLI - AWS SDK 程式碼範例

文件範例儲存庫中有更多 AWS SDK可用的範例。 AWS SDK GitHub

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

CreateQueue 搭配 AWS SDK或 使用 CLI

下列程式碼範例示範如何使用 CreateQueue

動作範例是大型程式的程式碼摘錄,必須在內容中執行。您可以在下列程式碼範例的內容中看到此動作:

.NET
AWS SDK for .NET
注意

還有更多 。 GitHub尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

建立具有特定名稱的佇列。

/// <summary> /// Create a queue with a specific name. /// </summary> /// <param name="queueName">The name for the queue.</param> /// <param name="useFifoQueue">True to use a FIFO queue.</param> /// <returns>The url for the queue.</returns> public async Task<string> CreateQueueWithName(string queueName, bool useFifoQueue) { int maxMessage = 256 * 1024; var queueAttributes = new Dictionary<string, string> { { QueueAttributeName.MaximumMessageSize, maxMessage.ToString() } }; var createQueueRequest = new CreateQueueRequest() { QueueName = queueName, Attributes = queueAttributes }; if (useFifoQueue) { // Update the name if it is not correct for a FIFO queue. if (!queueName.EndsWith(".fifo")) { createQueueRequest.QueueName = queueName + ".fifo"; } // Add an attribute for a FIFO queue. createQueueRequest.Attributes.Add( QueueAttributeName.FifoQueue, "true"); } var createResponse = await _amazonSQSClient.CreateQueueAsync( new CreateQueueRequest() { QueueName = queueName }); return createResponse.QueueUrl; }

建立 Amazon SQS佇列並傳送訊息。

using System; using System.Collections.Generic; using System.Threading.Tasks; using Amazon; using Amazon.SQS; using Amazon.SQS.Model; public class CreateSendExample { // Specify your AWS Region (an example Region is shown). private static readonly string QueueName = "Example_Queue"; private static readonly RegionEndpoint ServiceRegion = RegionEndpoint.USWest2; private static IAmazonSQS client; public static async Task Main() { client = new AmazonSQSClient(ServiceRegion); var createQueueResponse = await CreateQueue(client, QueueName); string queueUrl = createQueueResponse.QueueUrl; Dictionary<string, MessageAttributeValue> messageAttributes = new Dictionary<string, MessageAttributeValue> { { "Title", new MessageAttributeValue { DataType = "String", StringValue = "The Whistler" } }, { "Author", new MessageAttributeValue { DataType = "String", StringValue = "John Grisham" } }, { "WeeksOn", new MessageAttributeValue { DataType = "Number", StringValue = "6" } }, }; string messageBody = "Information about current NY Times fiction bestseller for week of 12/11/2016."; var sendMsgResponse = await SendMessage(client, queueUrl, messageBody, messageAttributes); } /// <summary> /// Creates a new Amazon SQS queue using the queue name passed to it /// in queueName. /// </summary> /// <param name="client">An SQS client object used to send the message.</param> /// <param name="queueName">A string representing the name of the queue /// to create.</param> /// <returns>A CreateQueueResponse that contains information about the /// newly created queue.</returns> public static async Task<CreateQueueResponse> CreateQueue(IAmazonSQS client, string queueName) { var request = new CreateQueueRequest { QueueName = queueName, Attributes = new Dictionary<string, string> { { "DelaySeconds", "60" }, { "MessageRetentionPeriod", "86400" }, }, }; var response = await client.CreateQueueAsync(request); Console.WriteLine($"Created a queue with URL : {response.QueueUrl}"); return response; } /// <summary> /// Sends a message to an SQS queue. /// </summary> /// <param name="client">An SQS client object used to send the message.</param> /// <param name="queueUrl">The URL of the queue to which to send the /// message.</param> /// <param name="messageBody">A string representing the body of the /// message to be sent to the queue.</param> /// <param name="messageAttributes">Attributes for the message to be /// sent to the queue.</param> /// <returns>A SendMessageResponse object that contains information /// about the message that was sent.</returns> public static async Task<SendMessageResponse> SendMessage( IAmazonSQS client, string queueUrl, string messageBody, Dictionary<string, MessageAttributeValue> messageAttributes) { var sendMessageRequest = new SendMessageRequest { DelaySeconds = 10, MessageAttributes = messageAttributes, MessageBody = messageBody, QueueUrl = queueUrl, }; var response = await client.SendMessageAsync(sendMessageRequest); Console.WriteLine($"Sent a message with id : {response.MessageId}"); return response; } }
  • 如需API詳細資訊,請參閱 參考 CreateQueue中的 。 AWS SDK for .NET API

C++
SDK 適用於 C++
注意

還有更多 。 GitHub尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region (overrides config file). // clientConfig.region = "us-east-1"; //! Create an Amazon Simple Queue Service (Amazon SQS) queue. /*! \param queueName: An Amazon SQS queue name. \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::SQS::createQueue(const Aws::String &queueName, const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::SQS::SQSClient sqsClient(clientConfiguration); Aws::SQS::Model::CreateQueueRequest request; request.SetQueueName(queueName); const Aws::SQS::Model::CreateQueueOutcome outcome = sqsClient.CreateQueue(request); if (outcome.IsSuccess()) { std::cout << "Successfully created queue " << queueName << " with a queue URL " << outcome.GetResult().GetQueueUrl() << "." << std::endl; } else { std::cerr << "Error creating queue " << queueName << ": " << outcome.GetError().GetMessage() << std::endl; } return outcome.IsSuccess(); }
  • 如需API詳細資訊,請參閱 參考 CreateQueue中的 。 AWS SDK for C++ API

CLI
AWS CLI

建立佇列

此範例會建立具有指定名稱的佇列,將訊息保留期設定為 3 天 (3 天 * 24 小時 * 60 分鐘 * 60 秒),並將佇列的無效字母佇列設定為具有最大接收計數為 1,000 則訊息的指定佇列。

命令:

aws sqs create-queue --queue-name MyQueue --attributes file://create-queue.json

輸入檔案 (create-queue.json):

{ "RedrivePolicy": "{\"deadLetterTargetArn\":\"arn:aws:sqs:us-east-1:80398EXAMPLE:MyDeadLetterQueue\",\"maxReceiveCount\":\"1000\"}", "MessageRetentionPeriod": "259200" }

輸出:

{ "QueueUrl": "https://queue.amazonaws.com/80398EXAMPLE/MyQueue" }
  • 如需API詳細資訊,請參閱 命令參考 CreateQueue中的 。 AWS CLI

Go
SDK for Go V2
注意

還有更多 。 GitHub尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

// SqsActions encapsulates the Amazon Simple Queue Service (Amazon SQS) actions // used in the examples. type SqsActions struct { SqsClient *sqs.Client } // CreateQueue creates an Amazon SQS queue with the specified name. You can specify // whether the queue is created as a FIFO queue. func (actor SqsActions) CreateQueue(queueName string, isFifoQueue bool) (string, error) { var queueUrl string queueAttributes := map[string]string{} if isFifoQueue { queueAttributes["FifoQueue"] = "true" } queue, err := actor.SqsClient.CreateQueue(context.TODO(), &sqs.CreateQueueInput{ QueueName: aws.String(queueName), Attributes: queueAttributes, }) if err != nil { log.Printf("Couldn't create queue %v. Here's why: %v\n", queueName, err) } else { queueUrl = *queue.QueueUrl } return queueUrl, err }
  • 如需API詳細資訊,請參閱 參考 CreateQueue中的 。 AWS SDK for Go API

Java
SDK 適用於 Java 2.x
注意

還有更多 。 GitHub尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sqs.SqsClient; import software.amazon.awssdk.services.sqs.model.ChangeMessageVisibilityRequest; import software.amazon.awssdk.services.sqs.model.CreateQueueRequest; import software.amazon.awssdk.services.sqs.model.DeleteMessageRequest; import software.amazon.awssdk.services.sqs.model.GetQueueUrlRequest; import software.amazon.awssdk.services.sqs.model.GetQueueUrlResponse; import software.amazon.awssdk.services.sqs.model.ListQueuesRequest; import software.amazon.awssdk.services.sqs.model.ListQueuesResponse; import software.amazon.awssdk.services.sqs.model.Message; import software.amazon.awssdk.services.sqs.model.ReceiveMessageRequest; import software.amazon.awssdk.services.sqs.model.SendMessageBatchRequest; import software.amazon.awssdk.services.sqs.model.SendMessageBatchRequestEntry; import software.amazon.awssdk.services.sqs.model.SendMessageRequest; import software.amazon.awssdk.services.sqs.model.SqsException; import java.util.List; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class SQSExample { public static void main(String[] args) { String queueName = "queue" + System.currentTimeMillis(); SqsClient sqsClient = SqsClient.builder() .region(Region.US_WEST_2) .build(); // Perform various tasks on the Amazon SQS queue. String queueUrl = createQueue(sqsClient, queueName); listQueues(sqsClient); listQueuesFilter(sqsClient, queueUrl); List<Message> messages = receiveMessages(sqsClient, queueUrl); sendBatchMessages(sqsClient, queueUrl); changeMessages(sqsClient, queueUrl, messages); deleteMessages(sqsClient, queueUrl, messages); sqsClient.close(); } public static String createQueue(SqsClient sqsClient, String queueName) { try { System.out.println("\nCreate Queue"); CreateQueueRequest createQueueRequest = CreateQueueRequest.builder() .queueName(queueName) .build(); sqsClient.createQueue(createQueueRequest); System.out.println("\nGet queue url"); GetQueueUrlResponse getQueueUrlResponse = sqsClient .getQueueUrl(GetQueueUrlRequest.builder().queueName(queueName).build()); return getQueueUrlResponse.queueUrl(); } catch (SqsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return ""; } public static void listQueues(SqsClient sqsClient) { System.out.println("\nList Queues"); String prefix = "que"; try { ListQueuesRequest listQueuesRequest = ListQueuesRequest.builder().queueNamePrefix(prefix).build(); ListQueuesResponse listQueuesResponse = sqsClient.listQueues(listQueuesRequest); for (String url : listQueuesResponse.queueUrls()) { System.out.println(url); } } catch (SqsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } public static void listQueuesFilter(SqsClient sqsClient, String queueUrl) { // List queues with filters String namePrefix = "queue"; ListQueuesRequest filterListRequest = ListQueuesRequest.builder() .queueNamePrefix(namePrefix) .build(); ListQueuesResponse listQueuesFilteredResponse = sqsClient.listQueues(filterListRequest); System.out.println("Queue URLs with prefix: " + namePrefix); for (String url : listQueuesFilteredResponse.queueUrls()) { System.out.println(url); } System.out.println("\nSend message"); try { sqsClient.sendMessage(SendMessageRequest.builder() .queueUrl(queueUrl) .messageBody("Hello world!") .delaySeconds(10) .build()); } catch (SqsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } public static void sendBatchMessages(SqsClient sqsClient, String queueUrl) { System.out.println("\nSend multiple messages"); try { SendMessageBatchRequest sendMessageBatchRequest = SendMessageBatchRequest.builder() .queueUrl(queueUrl) .entries(SendMessageBatchRequestEntry.builder().id("id1").messageBody("Hello from msg 1").build(), SendMessageBatchRequestEntry.builder().id("id2").messageBody("msg 2").delaySeconds(10) .build()) .build(); sqsClient.sendMessageBatch(sendMessageBatchRequest); } catch (SqsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } public static List<Message> receiveMessages(SqsClient sqsClient, String queueUrl) { System.out.println("\nReceive messages"); try { ReceiveMessageRequest receiveMessageRequest = ReceiveMessageRequest.builder() .queueUrl(queueUrl) .maxNumberOfMessages(5) .build(); return sqsClient.receiveMessage(receiveMessageRequest).messages(); } catch (SqsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return null; } public static void changeMessages(SqsClient sqsClient, String queueUrl, List<Message> messages) { System.out.println("\nChange Message Visibility"); try { for (Message message : messages) { ChangeMessageVisibilityRequest req = ChangeMessageVisibilityRequest.builder() .queueUrl(queueUrl) .receiptHandle(message.receiptHandle()) .visibilityTimeout(100) .build(); sqsClient.changeMessageVisibility(req); } } catch (SqsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } public static void deleteMessages(SqsClient sqsClient, String queueUrl, List<Message> messages) { System.out.println("\nDelete Messages"); try { for (Message message : messages) { DeleteMessageRequest deleteMessageRequest = DeleteMessageRequest.builder() .queueUrl(queueUrl) .receiptHandle(message.receiptHandle()) .build(); sqsClient.deleteMessage(deleteMessageRequest); } } catch (SqsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }
  • 如需API詳細資訊,請參閱 參考 CreateQueue中的 。 AWS SDK for Java 2.x API

JavaScript
SDK 適用於 JavaScript (v3)
注意

還有更多 。 GitHub尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

建立 Amazon SQS標準佇列。

import { CreateQueueCommand, SQSClient } from "@aws-sdk/client-sqs"; const client = new SQSClient({}); const SQS_QUEUE_NAME = "test-queue"; export const main = async (sqsQueueName = SQS_QUEUE_NAME) => { const command = new CreateQueueCommand({ QueueName: sqsQueueName, Attributes: { DelaySeconds: "60", MessageRetentionPeriod: "86400", }, }); const response = await client.send(command); console.log(response); return response; };

建立具有長輪詢的 Amazon SQS佇列。

import { CreateQueueCommand, SQSClient } from "@aws-sdk/client-sqs"; const client = new SQSClient({}); const SQS_QUEUE_NAME = "queue_name"; export const main = async (queueName = SQS_QUEUE_NAME) => { const response = await client.send( new CreateQueueCommand({ QueueName: queueName, Attributes: { // When the wait time for the ReceiveMessage API action is greater than 0, // long polling is in effect. The maximum long polling wait time is 20 // seconds. Long polling helps reduce the cost of using Amazon SQS by, // eliminating the number of empty responses and false empty responses. // https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-short-and-long-polling.html ReceiveMessageWaitTimeSeconds: "20", }, }), ); console.log(response); return response; };
SDK 適用於 JavaScript (v2)
注意

還有更多 。 GitHub尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

建立 Amazon SQS標準佇列。

// Load the AWS SDK for Node.js var AWS = require("aws-sdk"); // Set the region AWS.config.update({ region: "REGION" }); // Create an SQS service object var sqs = new AWS.SQS({ apiVersion: "2012-11-05" }); var params = { QueueName: "SQS_QUEUE_NAME", Attributes: { DelaySeconds: "60", MessageRetentionPeriod: "86400", }, }; sqs.createQueue(params, function (err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data.QueueUrl); } });

建立等待訊息到達的 Amazon SQS佇列。

// Load the AWS SDK for Node.js var AWS = require("aws-sdk"); // Set the region AWS.config.update({ region: "REGION" }); // Create the SQS service object var sqs = new AWS.SQS({ apiVersion: "2012-11-05" }); var params = { QueueName: "SQS_QUEUE_NAME", Attributes: { ReceiveMessageWaitTimeSeconds: "20", }, }; sqs.createQueue(params, function (err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data.QueueUrl); } });
Kotlin
SDK 適用於 Kotlin
注意

還有更多 。 GitHub尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

suspend fun createQueue(queueNameVal: String): String { println("Create Queue") val createQueueRequest = CreateQueueRequest { queueName = queueNameVal } SqsClient { region = "us-east-1" }.use { sqsClient -> sqsClient.createQueue(createQueueRequest) println("Get queue url") val getQueueUrlRequest = GetQueueUrlRequest { queueName = queueNameVal } val getQueueUrlResponse = sqsClient.getQueueUrl(getQueueUrlRequest) return getQueueUrlResponse.queueUrl.toString() } }
  • 如需API詳細資訊,請參閱CreateQueue中的 AWS SDK for Kotlin API參考

PowerShell
適用於 的工具 PowerShell

範例 1:此範例會建立具有指定名稱的佇列。

New-SQSQueue -QueueName MyQueue

輸出:

https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue
  • 如需API詳細資訊,請參閱 AWS Tools for PowerShell Cmdlet 參考 CreateQueue中的 。

Python
SDK for Python (Boto3)
注意

還有更多 。 GitHub尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

def create_queue(name, attributes=None): """ Creates an Amazon SQS queue. :param name: The name of the queue. This is part of the URL assigned to the queue. :param attributes: The attributes of the queue, such as maximum message size or whether it's a FIFO queue. :return: A Queue object that contains metadata about the queue and that can be used to perform queue operations like sending and receiving messages. """ if not attributes: attributes = {} try: queue = sqs.create_queue(QueueName=name, Attributes=attributes) logger.info("Created queue '%s' with URL=%s", name, queue.url) except ClientError as error: logger.exception("Couldn't create queue named '%s'.", name) raise error else: return queue
  • 如需API詳細資訊,請參閱 CreateQueue 中的 AWS SDK for Python (Boto3) API參考

Ruby
SDK 適用於 Ruby
注意

還有更多 。 GitHub尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

# This code example demonstrates how to create a queue in Amazon Simple Queue Service (Amazon SQS). require 'aws-sdk-sqs' # @param sqs_client [Aws::SQS::Client] An initialized Amazon SQS client. # @param queue_name [String] The name of the queue. # @return [Boolean] true if the queue was created; otherwise, false. # @example # exit 1 unless queue_created?( # Aws::SQS::Client.new(region: 'us-west-2'), # 'my-queue' # ) def queue_created?(sqs_client, queue_name) sqs_client.create_queue(queue_name: queue_name) true rescue StandardError => e puts "Error creating queue: #{e.message}" false end # Full example call: # Replace us-west-2 with the AWS Region you're using for Amazon SQS. def run_me region = 'us-west-2' queue_name = 'my-queue' sqs_client = Aws::SQS::Client.new(region: region) puts "Creating the queue named '#{queue_name}'..." if queue_created?(sqs_client, queue_name) puts 'Queue created.' else puts 'Queue not created.' end end # Example usage: run_me if $PROGRAM_NAME == __FILE__
  • 如需API詳細資訊,請參閱 參考 CreateQueue中的 。 AWS SDK for Ruby API

SAP ABAP
SDK 適用於 SAP ABAP
注意

還有更多 。 GitHub尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

建立 Amazon SQS標準佇列。

TRY. oo_result = lo_sqs->createqueue( iv_queuename = iv_queue_name ). " oo_result is returned for testing purposes. " MESSAGE 'SQS queue created.' TYPE 'I'. CATCH /aws1/cx_sqsqueuedeldrecently. MESSAGE 'After deleting a queue, wait 60 seconds before creating another queue with the same name.' TYPE 'E'. CATCH /aws1/cx_sqsqueuenameexists. MESSAGE 'A queue with this name already exists.' TYPE 'E'. ENDTRY.

建立等待訊息到達的 Amazon SQS佇列。

TRY. DATA lt_attributes TYPE /aws1/cl_sqsqueueattrmap_w=>tt_queueattributemap. DATA ls_attribute TYPE /aws1/cl_sqsqueueattrmap_w=>ts_queueattributemap_maprow. ls_attribute-key = 'ReceiveMessageWaitTimeSeconds'. " Time in seconds for long polling, such as how long the call waits for a message to arrive in the queue before returning. " ls_attribute-value = NEW /aws1/cl_sqsqueueattrmap_w( iv_value = iv_wait_time ). INSERT ls_attribute INTO TABLE lt_attributes. oo_result = lo_sqs->createqueue( " oo_result is returned for testing purposes. " iv_queuename = iv_queue_name it_attributes = lt_attributes ). MESSAGE 'SQS queue created.' TYPE 'I'. CATCH /aws1/cx_sqsqueuedeldrecently. MESSAGE 'After deleting a queue, wait 60 seconds before creating another queue with the same name.' TYPE 'E'. CATCH /aws1/cx_sqsqueuenameexists. MESSAGE 'A queue with this name already exists.' TYPE 'E'. ENDTRY.
  • 如需API詳細資訊,請參閱CreateQueue中的 AWS SDK 以取得SAPABAPAPI參考