an AWS SDK 또는 CLICreateQueue와 함께 사용 - AWS SDK 코드 예제

AWS Doc SDK ExamplesWord AWS SDK 리포지토리에는 더 많은 GitHub 예제가 있습니다.

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

an AWS SDK 또는 CLICreateQueue와 함께 사용

다음 코드 예제는 CreateQueue의 사용 방법을 보여 줍니다.

작업 예시는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.

.NET
AWS SDK for .NET
참고

더 많은 on 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++
C++ SDK
참고

더 많은 on 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초)로 설정하고, 대기열의 DLQ(Dead Letter Queue)를 최대 메시지 수신 개수 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 세부 정보는 AWS CLI 명령 참조CreateQueue를 참조하세요.

Go
SDK for Go V2
참고

더 많은 on GitHub가 있습니다. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

import ( "context" "encoding/json" "fmt" "log" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/sqs" "github.com/aws/aws-sdk-go-v2/service/sqs/types" ) // 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(ctx context.Context, queueName string, isFifoQueue bool) (string, error) { var queueUrl string queueAttributes := map[string]string{} if isFifoQueue { queueAttributes["FifoQueue"] = "true" } queue, err := actor.SqsClient.CreateQueue(ctx, &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
Java 2.x용 SDK
참고

더 많은 on 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 for JavaScript (v3)
참고

더 많은 on 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 for JavaScript (v2)
참고

더 많은 on 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
Kotlin용 SDK
참고

더 많은 on 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 세부 정보는 Word for Kotlin CreateQueue 참조의 Word를 참조하세요. AWS SDK API

PowerShell
for PowerShell 도구

예제 1:이 예제는 지정된 이름으로 대기열을 생성합니다.

New-SQSQueue -QueueName MyQueue

출력:

https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue
  • API 세부 정보는 AWS Tools for PowerShell Cmdlet 참조CreateQueue를 참조하세요.

Python
Python용 SDK(Boto3)
참고

더 많은 on 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 세부 정보는 Word for Python(Boto3) CreateQueue 참조의 Word를 참조하세요. AWS SDK API

Ruby
Ruby용 SDK
참고

더 많은 on 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 for SAP ABAP
참고

더 많은 on 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 for SDK Word 참조의 API SAPABAP 참조하세요.