AWS SDK を使用して Amazon SQS キューにメッセージを送信する - AWS SDK コードサンプル

Doc AWS SDK Examples リポジトリには、他にも SDK の例があります。 AWS GitHub

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

AWS SDK を使用して Amazon SQS キューにメッセージを送信する

次のコード例は、Amazon SQS キューにメッセージを送信する方法を示しています。

.NET
AWS SDK for .NET
注記

には他にもがあります 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 の詳細については、「 API リファレンスSendMessage」の「」を参照してください。 AWS SDK for .NET

C++
SDK for C++
注記

には他にもがあります 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 の詳細については、「 API リファレンスSendMessage」の「」を参照してください。 AWS SDK for C++

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 の詳細については、「 コマンドリファレンスSendMessage」の「」を参照してください。 AWS CLI

Java
SDK for Java 2.x
注記

には他にもがあります 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 の詳細については、「 API リファレンスSendMessage」の「」を参照してください。 AWS SDK for Java 2.x

JavaScript
SDK for JavaScript (v3)
注記

には他にもがあります 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)
注記

には他にもがあります 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
SDK for Kotlin
注記

には他にもがあります 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 の詳細については、SendMessageAWS「 SDK for Kotlin API リファレンス」の「」を参照してください。

Python
SDK for Python (Boto3)
注記

には他にもがあります 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 の詳細については、SendMessageAWS「 SDK for Python (Boto3) API リファレンス」の「」を参照してください。

Ruby
SDK for Ruby
注記

には他にもがあります 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 の詳細については、「 API リファレンスSendMessage」の「」を参照してください。 AWS SDK for Ruby

Rust
SDK for Rust
注記

には他にもがあります 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 の詳細については、SendMessageAWS「 SDK for Rust API リファレンス」の「」を参照してください。

SAP ABAP
SDK for SAP ABAP
注記

には他にもがあります 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 の詳細については、SendMessageAWS「 SDK for SAP ABAP API リファレンス」の「」を参照してください。