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

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

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

an AWS SDK 또는 CLISendMessage와 함께 사용

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

.NET
AWS SDK for .NET
참고

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

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 세부 정보는 SendMessage 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"; //! Send a message to an Amazon Simple Queue Service (Amazon SQS) queue. /*! \param queueUrl: An Amazon SQS queue URL. \param messageBody: A message body. \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::SQS::sendMessage(const Aws::String &queueUrl, const Aws::String &messageBody, const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::SQS::SQSClient sqsClient(clientConfiguration); Aws::SQS::Model::SendMessageRequest request; request.SetQueueUrl(queueUrl); request.SetMessageBody(messageBody); const Aws::SQS::Model::SendMessageOutcome outcome = sqsClient.SendMessage(request); if (outcome.IsSuccess()) { std::cout << "Successfully sent message to " << queueUrl << std::endl; } else { std::cerr << "Error sending message to " << queueUrl << ": " << outcome.GetError().GetMessage() << std::endl; } return outcome.IsSuccess(); }
  • API 세부 정보는 SendMessage AWS SDK for C++ 참조의 API를 참조하세요.

CLI
AWS CLI

메시지를 전송하려면

이 예시에서는 지정된 메시지 본문, 지연 기간 및 메시지 속성이 설정된 메시지를 지정된 대기열로 보냅니다.

명령:

aws sqs send-message --queue-url https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue --message-body "Information about the largest city in Any Region." --delay-seconds 10 --message-attributes file://send-message.json

입력 파일(send-message.json):

{ "City": { "DataType": "String", "StringValue": "Any City" }, "Greeting": { "DataType": "Binary", "BinaryValue": "Hello, World!" }, "Population": { "DataType": "Number", "StringValue": "1250800" } }

출력:

{ "MD5OfMessageBody": "51b0a325...39163aa0", "MD5OfMessageAttributes": "00484c68...59e48f06", "MessageId": "da68f62c-0c07-4bee-bf5f-7e856EXAMPLE" }
  • API 세부 정보는 AWS CLI 명령 참조SendMessage를 참조하세요.

Java
Java 2.x용 SDK
참고

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

import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sqs.SqsClient; import software.amazon.awssdk.services.sqs.model.CreateQueueRequest; import software.amazon.awssdk.services.sqs.model.GetQueueUrlRequest; import software.amazon.awssdk.services.sqs.model.SendMessageRequest; import software.amazon.awssdk.services.sqs.model.SqsException; /** * 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 SendMessages { public static void main(String[] args) { final String usage = """ Usage: <queueName> <message> Where: queueName - The name of the queue. message - The message to send. """; if (args.length != 2) { System.out.println(usage); System.exit(1); } String queueName = args[0]; String message = args[1]; SqsClient sqsClient = SqsClient.builder() .region(Region.US_WEST_2) .build(); sendMessage(sqsClient, queueName, message); sqsClient.close(); } public static void sendMessage(SqsClient sqsClient, String queueName, String message) { try { CreateQueueRequest request = CreateQueueRequest.builder() .queueName(queueName) .build(); sqsClient.createQueue(request); GetQueueUrlRequest getQueueRequest = GetQueueUrlRequest.builder() .queueName(queueName) .build(); String queueUrl = sqsClient.getQueueUrl(getQueueRequest).queueUrl(); SendMessageRequest sendMsgRequest = SendMessageRequest.builder() .queueUrl(queueUrl) .messageBody(message) .delaySeconds(5) .build(); sqsClient.sendMessage(sendMsgRequest); } catch (SqsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }
  • API 세부 정보는 SendMessage AWS SDK for Java 2.x 참조의 API를 참조하세요.

JavaScript
SDK for JavaScript (v3)
참고

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

Amazon SQS 대기열로 메시지를 보냅니다.

import { SendMessageCommand, SQSClient } from "@aws-sdk/client-sqs"; const client = new SQSClient({}); const SQS_QUEUE_URL = "queue_url"; export const main = async (sqsQueueUrl = SQS_QUEUE_URL) => { const command = new SendMessageCommand({ QueueUrl: sqsQueueUrl, DelaySeconds: 10, MessageAttributes: { Title: { DataType: "String", StringValue: "The Whistler", }, Author: { DataType: "String", StringValue: "John Grisham", }, WeeksOn: { DataType: "Number", StringValue: "6", }, }, MessageBody: "Information about current NY Times fiction bestseller for week of 12/11/2016.", }); const response = await client.send(command); 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 = { // Remove DelaySeconds parameter and value for FIFO queues DelaySeconds: 10, MessageAttributes: { Title: { DataType: "String", StringValue: "The Whistler", }, Author: { DataType: "String", StringValue: "John Grisham", }, WeeksOn: { DataType: "Number", StringValue: "6", }, }, MessageBody: "Information about current NY Times fiction bestseller for week of 12/11/2016.", // MessageDeduplicationId: "TheWhistler", // Required for FIFO queues // MessageGroupId: "Group1", // Required for FIFO queues QueueUrl: "SQS_QUEUE_URL", }; sqs.sendMessage(params, function (err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data.MessageId); } });
Kotlin
Kotlin용 SDK
참고

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

suspend fun sendMessages( queueUrlVal: String, message: String, ) { println("Sending multiple messages") println("\nSend message") val sendRequest = SendMessageRequest { queueUrl = queueUrlVal messageBody = message delaySeconds = 10 } SqsClient { region = "us-east-1" }.use { sqsClient -> sqsClient.sendMessage(sendRequest) println("A single message was successfully sent.") } } suspend fun sendBatchMessages(queueUrlVal: String?) { println("Sending multiple messages") val msg1 = SendMessageBatchRequestEntry { id = "id1" messageBody = "Hello from msg 1" } val msg2 = SendMessageBatchRequestEntry { id = "id2" messageBody = "Hello from msg 2" } val sendMessageBatchRequest = SendMessageBatchRequest { queueUrl = queueUrlVal entries = listOf(msg1, msg2) } SqsClient { region = "us-east-1" }.use { sqsClient -> sqsClient.sendMessageBatch(sendMessageBatchRequest) println("Batch message were successfully sent.") } }
  • API 세부 정보는 Word for Kotlin SendMessage 참조의 Word를 참조하세요. AWS SDK API

PowerShell
for PowerShell 도구

예제 1:이 예제에서는 지정된 속성과 메시지 본문이 포함된 메시지를 메시지 전송이 10초 동안 지연된 상태로 지정된 대기열로 보냅니다.

$cityAttributeValue = New-Object Amazon.SQS.Model.MessageAttributeValue $cityAttributeValue.DataType = "String" $cityAttributeValue.StringValue = "AnyCity" $populationAttributeValue = New-Object Amazon.SQS.Model.MessageAttributeValue $populationAttributeValue.DataType = "Number" $populationAttributeValue.StringValue = "1250800" $messageAttributes = New-Object System.Collections.Hashtable $messageAttributes.Add("City", $cityAttributeValue) $messageAttributes.Add("Population", $populationAttributeValue) Send-SQSMessage -DelayInSeconds 10 -MessageAttributes $messageAttributes -MessageBody "Information about the largest city in Any Region." -QueueUrl https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue

출력:

MD5OfMessageAttributes MD5OfMessageBody MessageId ---------------------- ---------------- --------- 1d3e51347bc042efbdf6dda31EXAMPLE 51b0a3256d59467f973009b73EXAMPLE c35fed8f-c739-4d0c-818b-1820eEXAMPLE
  • API 세부 정보는 AWS Tools for PowerShell Cmdlet 참조SendMessage를 참조하세요.

Python
Python용 SDK(Boto3)
참고

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

def send_message(queue, message_body, message_attributes=None): """ Send a message to an Amazon SQS queue. :param queue: The queue that receives the message. :param message_body: The body text of the message. :param message_attributes: Custom attributes of the message. These are key-value pairs that can be whatever you want. :return: The response from SQS that contains the assigned message ID. """ if not message_attributes: message_attributes = {} try: response = queue.send_message( MessageBody=message_body, MessageAttributes=message_attributes ) except ClientError as error: logger.exception("Send message failed: %s", message_body) raise error else: return response
  • API 세부 정보는 Word for Python(Boto3) SendMessage 참조의 Word를 참조하세요. AWS SDK API

Ruby
Ruby용 SDK
참고

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

require 'aws-sdk-sqs' require 'aws-sdk-sts' # @param sqs_client [Aws::SQS::Client] An initialized Amazon SQS client. # @param queue_url [String] The URL of the queue. # @param message_body [String] The contents of the message to be sent. # @return [Boolean] true if the message was sent; otherwise, false. # @example # exit 1 unless message_sent?( # Aws::SQS::Client.new(region: 'us-west-2'), # 'https://sqs.us-west-2.amazonaws.com/111111111111/my-queue', # 'This is my message.' # ) def message_sent?(sqs_client, queue_url, message_body) sqs_client.send_message( queue_url: queue_url, message_body: message_body ) true rescue StandardError => e puts "Error sending message: #{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' message_body = 'This is my message.' sts_client = Aws::STS::Client.new(region: region) # For example: # 'https://sqs.us-west-2.amazonaws.com/111111111111/my-queue' queue_url = "https://sqs.#{region}.amazonaws.com/#{sts_client.get_caller_identity.account}/#{queue_name}" sqs_client = Aws::SQS::Client.new(region: region) puts "Sending a message to the queue named '#{queue_name}'..." if message_sent?(sqs_client, queue_url, message_body) puts 'Message sent.' else puts 'Message not sent.' end end # Example usage: run_me if $PROGRAM_NAME == __FILE__
  • API 세부 정보는 SendMessage AWS SDK for Ruby 참조의 API를 참조하세요.

Rust
Rust용 SDK
참고

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

async fn send(client: &Client, queue_url: &String, message: &SQSMessage) -> Result<(), Error> { println!("Sending message to queue with URL: {}", queue_url); let rsp = client .send_message() .queue_url(queue_url) .message_body(&message.body) // If the queue is FIFO, you need to set .message_deduplication_id // and message_group_id or configure the queue for ContentBasedDeduplication. .send() .await?; println!("Send message to the queue: {:#?}", rsp); Ok(()) }
  • API 세부 정보는 Word for Rust SendMessage 참조의 Word를 참조하세요. AWS SDK API

SAP ABAP
SDK for SAP ABAP
참고

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

TRY. oo_result = lo_sqs->sendmessage( " oo_result is returned for testing purposes. " iv_queueurl = iv_queue_url iv_messagebody = iv_message ). MESSAGE 'Message sent to SQS queue.' TYPE 'I'. CATCH /aws1/cx_sqsinvalidmsgconts. MESSAGE 'Message contains non-valid characters.' TYPE 'E'. CATCH /aws1/cx_sqsunsupportedop. MESSAGE 'Operation not supported.' TYPE 'E'. ENDTRY.
  • API 세부 정보는 SendMessage AWS for SDK Word 참조의 API SAPABAP 참조하세요.