AWSDocAWS SDKGitHub サンプルリポジトリには、さらに多くの SDK サンプルがあります
翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。
AWSSDK を使用して Amazon SQSキューを作成する
次のコード例は、Amazon SQS キューを作成する方法を示しています。
- .NET
-
- AWS SDK for .NET
-
注記
他にもありますGitHub。用例一覧を検索し、AWS コード例リポジトリ
での設定と実行の方法を確認してください。 using System; using System.Collections.Generic; using System.Threading.Tasks; using Amazon.SQS; using Amazon.SQS.Model; public class CreateQueue { /// <summary> /// Initializes the Amazon SQS client object and then calls the /// CreateQueueAsync method to create the new queue. If the call is /// successful, it displays the URL of the new queue on the console. /// </summary> public static async Task Main() { // If the Amazon SQS message queue is not in the same AWS Region as your // default user, you need to provide the AWS Region as a parameter to the // client constructor. var client = new AmazonSQSClient(); string queueName = "New-Example-Queue"; int maxMessage = 256 * 1024; var attrs = new Dictionary<string, string> { { QueueAttributeName.DelaySeconds, TimeSpan.FromSeconds(5).TotalSeconds.ToString() }, { QueueAttributeName.MaximumMessageSize, maxMessage.ToString() }, { QueueAttributeName.MessageRetentionPeriod, TimeSpan.FromDays(4).TotalSeconds.ToString() }, { QueueAttributeName.ReceiveMessageWaitTimeSeconds, TimeSpan.FromSeconds(5).TotalSeconds.ToString() }, { QueueAttributeName.VisibilityTimeout, TimeSpan.FromHours(12).TotalSeconds.ToString() }, }; var request = new CreateQueueRequest { Attributes = attrs, QueueName = queueName, }; var response = await client.CreateQueueAsync(request); if (response.HttpStatusCode == System.Net.HttpStatusCode.OK) { Console.WriteLine("Successfully created Amazon SQS queue."); Console.WriteLine($"Queue URL: {response.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 の詳細については、AWS SDK for .NETAPI CreateQueueリファレンスのを参照してください。
-
- C++
-
- SDK for 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 の詳細については、AWS SDK for C++API CreateQueueリファレンスのを参照してください。
-
- Go
-
- SDK for Go V2
-
注記
他にもありますGitHub。用例一覧を検索し、AWS コード例リポジトリ
での設定と実行の方法を確認してください。 package main import ( "context" "flag" "fmt" "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/service/sqs" ) // SQSCreateQueueAPI defines the interface for the CreateQueue function. // We use this interface to test the function using a mocked service. type SQSCreateQueueAPI interface { CreateQueue(ctx context.Context, params *sqs.CreateQueueInput, optFns ...func(*sqs.Options)) (*sqs.CreateQueueOutput, error) } // CreateQueue creates an Amazon SQS queue. // Inputs: // c is the context of the method call, which includes the AWS Region. // api is the interface that defines the method call. // input defines the input arguments to the service call. // Output: // If success, a CreateQueueOutput object containing the result of the service call and nil. // Otherwise, nil and an error from the call to CreateQueue. func CreateQueue(c context.Context, api SQSCreateQueueAPI, input *sqs.CreateQueueInput) (*sqs.CreateQueueOutput, error) { return api.CreateQueue(c, input) } func main() { queue := flag.String("q", "", "The name of the queue") flag.Parse() if *queue == "" { fmt.Println("You must supply a queue name (-q QUEUE") return } cfg, err := config.LoadDefaultConfig(context.TODO()) if err != nil { panic("configuration error, " + err.Error()) } client := sqs.NewFromConfig(cfg) input := &sqs.CreateQueueInput{ QueueName: queue, Attributes: map[string]string{ "DelaySeconds": "60", "MessageRetentionPeriod": "86400", }, } result, err := CreateQueue(context.TODO(), client, input) if err != nil { fmt.Println("Got an error creating the queue:") fmt.Println(err) return } fmt.Println("URL: " + *result.QueueUrl) }
-
API の詳細については、AWS SDK for GoAPI CreateQueue
リファレンスのを参照してください。
-
- Java
-
- SDK for Java 2.x
-
注記
他にもありますGitHub。用例一覧を検索し、AWS コード例リポジトリ
での設定と実行の方法を確認してください。 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 の詳細については、AWS SDK for Java 2.xAPI CreateQueueリファレンスのを参照してください。
-
- JavaScript
-
- SDK forJavaScript v3)
-
注記
他にもありますGitHub。用例一覧を検索し、AWS コード例リポジトリ
での設定と実行の方法を確認してください。 クライアントを作成します。
import { SQSClient } from "@aws-sdk/client-sqs"; // Set the AWS Region. const REGION = "REGION"; //e.g. "us-east-1" // Create SQS service object. const sqsClient = new SQSClient({ region: REGION }); export { sqsClient };
Amazon SQS スタンダードキューを作成します。
// Import required AWS SDK clients and commands for Node.js import { CreateQueueCommand } from "@aws-sdk/client-sqs"; import { sqsClient } from "./libs/sqsClient.js"; // Set the parameters const params = { QueueName: "SQS_QUEUE_NAME", //SQS_QUEUE_URL Attributes: { DelaySeconds: "60", // Number of seconds delay. MessageRetentionPeriod: "86400", // Number of seconds delay. }, }; const run = async () => { try { const data = await sqsClient.send(new CreateQueueCommand(params)); console.log("Success", data); return data; // For unit tests. } catch (err) { console.log("Error", err); } }; run();
メッセージが到着するのを待つ Amazon SQSキューを作成すします。
// Import required AWS SDK clients and commands for Node.js import { CreateQueueCommand } from "@aws-sdk/client-sqs"; import { sqsClient } from "./libs/sqsClient.js"; // Set the parameters const params = { QueueName: "SQS_QUEUE_NAME", //SQS_QUEUE_URL; e.g., 'https://sqs.REGION.amazonaws.com/ACCOUNT-ID/QUEUE-NAME' Attributes: { ReceiveMessageWaitTimeSeconds: "20", }, }; const run = async () => { try { const data = await sqsClient.send(new CreateQueueCommand(params)); console.log("Success", data); return data; // For unit tests. } catch (err) { console.error(err, err.stack); } }; run();
-
詳細については、AWS SDK for JavaScript デベロッパーガイドを参照してください。
-
API の詳細については、AWS SDK for JavaScriptAPI CreateQueueリファレンスのを参照してください。
-
- SDK forJavaScript 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); } });
-
詳細については、AWS SDK for JavaScript デベロッパーガイドを参照してください。
-
API の詳細については、AWS SDK for JavaScriptAPI CreateQueueリファレンスのを参照してください。
-
- Kotlin
-
- SDK for 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 の詳細については、「AWSSDK for Kotlin API リファレンス」を参照してください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 の詳細については、「AWSSDK for Python (Boto3) API リファレンス」のを参照してくださいCreateQueue。
-
- Ruby
-
- SDK for 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 run_me if $PROGRAM_NAME == __FILE__
-
API の詳細については、AWS SDK for RubyAPI CreateQueueリファレンスのを参照してください。
-
- SAP ABAP
-
- SDK for SAP ABAP
-
注記
これはデベロッパープレビューリリースの SDK に関するドキュメントです。SDK は変更される場合があるため、本稼働環境での使用はお勧めできません。
注記
他にもあります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 の詳細については、「CreateQueueSDK for SAP ABAP API リファレンス」の「AWSSDK for SAP ABAP API リファレンス」の
-