Gunakan ReceiveMessage dengan AWS SDK atau CLI - AWS Contoh Kode SDK

Ada lebih banyak contoh AWS SDK yang tersedia di repo Contoh SDK AWS Doc. GitHub

Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris.

Gunakan ReceiveMessage dengan AWS SDK atau CLI

Contoh kode berikut menunjukkan cara menggunakanReceiveMessage.

Contoh tindakan adalah kutipan kode dari program yang lebih besar dan harus dijalankan dalam konteks. Anda dapat melihat tindakan ini dalam konteks dalam contoh kode berikut:

.NET
AWS SDK for .NET
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di AWS Repositori Contoh Kode.

Menerima pesan dari antrian dengan menggunakan URL-nya.

/// <summary> /// Receive messages from a queue by its URL. /// </summary> /// <param name="queueUrl">The url of the queue.</param> /// <returns>The list of messages.</returns> public async Task<List<Message>> ReceiveMessagesByUrl(string queueUrl, int maxMessages) { // Setting WaitTimeSeconds to non-zero enables long polling. // For information about long polling, see // https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-short-and-long-polling.html var messageResponse = await _amazonSQSClient.ReceiveMessageAsync( new ReceiveMessageRequest() { QueueUrl = queueUrl, MaxNumberOfMessages = maxMessages, WaitTimeSeconds = 1 }); return messageResponse.Messages; }

Menerima pesan dari antrian Amazon SQS, lalu hapus pesan.

public static async Task Main() { // If the AWS Region you want to use is different from // the AWS Region defined for the default user, supply // the specify your AWS Region to the client constructor. var client = new AmazonSQSClient(); string queueName = "Example_Queue"; var queueUrl = await GetQueueUrl(client, queueName); Console.WriteLine($"The SQS queue's URL is {queueUrl}"); var response = await ReceiveAndDeleteMessage(client, queueUrl); Console.WriteLine($"Message: {response.Messages[0]}"); } /// <summary> /// Retrieve the queue URL for the queue named in the queueName /// property using the client object. /// </summary> /// <param name="client">The Amazon SQS client used to retrieve the /// queue URL.</param> /// <param name="queueName">A string representing name of the queue /// for which to retrieve the URL.</param> /// <returns>The URL of the queue.</returns> public static async Task<string> GetQueueUrl(IAmazonSQS client, string queueName) { var request = new GetQueueUrlRequest { QueueName = queueName, }; GetQueueUrlResponse response = await client.GetQueueUrlAsync(request); return response.QueueUrl; } /// <summary> /// Retrieves the message from the quque at the URL passed in the /// queueURL parameters using the client. /// </summary> /// <param name="client">The SQS client used to retrieve a message.</param> /// <param name="queueUrl">The URL of the queue from which to retrieve /// a message.</param> /// <returns>The response from the call to ReceiveMessageAsync.</returns> public static async Task<ReceiveMessageResponse> ReceiveAndDeleteMessage(IAmazonSQS client, string queueUrl) { // Receive a single message from the queue. var receiveMessageRequest = new ReceiveMessageRequest { AttributeNames = { "SentTimestamp" }, MaxNumberOfMessages = 1, MessageAttributeNames = { "All" }, QueueUrl = queueUrl, VisibilityTimeout = 0, WaitTimeSeconds = 0, }; var receiveMessageResponse = await client.ReceiveMessageAsync(receiveMessageRequest); // Delete the received message from the queue. var deleteMessageRequest = new DeleteMessageRequest { QueueUrl = queueUrl, ReceiptHandle = receiveMessageResponse.Messages[0].ReceiptHandle, }; await client.DeleteMessageAsync(deleteMessageRequest); return receiveMessageResponse; } }
  • Untuk detail API, lihat ReceiveMessagedi Referensi AWS SDK for .NET API.

C++
SDK untuk C++
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di AWS Repositori Contoh Kode.

Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region (overrides config file). // clientConfig.region = "us-east-1"; //! Receive a message from an Amazon Simple Queue Service (Amazon SQS) queue. /*! \param queueUrl: An Amazon SQS queue URL. \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::SQS::receiveMessage(const Aws::String &queueUrl, const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::SQS::SQSClient sqsClient(clientConfiguration); Aws::SQS::Model::ReceiveMessageRequest request; request.SetQueueUrl(queueUrl); request.SetMaxNumberOfMessages(1); const Aws::SQS::Model::ReceiveMessageOutcome outcome = sqsClient.ReceiveMessage( request); if (outcome.IsSuccess()) { const Aws::Vector<Aws::SQS::Model::Message> &messages = outcome.GetResult().GetMessages(); if (!messages.empty()) { const Aws::SQS::Model::Message &message = messages[0]; std::cout << "Received message:" << std::endl; std::cout << " MessageId: " << message.GetMessageId() << std::endl; std::cout << " ReceiptHandle: " << message.GetReceiptHandle() << std::endl; std::cout << " Body: " << message.GetBody() << std::endl << std::endl; } else { std::cout << "No messages received from queue " << queueUrl << std::endl; } } else { std::cerr << "Error receiving message from queue " << queueUrl << ": " << outcome.GetError().GetMessage() << std::endl; } return outcome.IsSuccess(); }
  • Untuk detail API, lihat ReceiveMessagedi Referensi AWS SDK for C++ API.

CLI
AWS CLI

Untuk menerima pesan

Contoh ini menerima hingga 10 pesan yang tersedia, mengembalikan semua atribut yang tersedia.

Perintah:

aws sqs receive-message --queue-url https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue --attribute-names All --message-attribute-names All --max-number-of-messages 10

Output:

{ "Messages": [ { "Body": "My first message.", "ReceiptHandle": "AQEBzbVv...fqNzFw==", "MD5OfBody": "1000f835...a35411fa", "MD5OfMessageAttributes": "9424c491...26bc3ae7", "MessageId": "d6790f8d-d575-4f01-bc51-40122EXAMPLE", "Attributes": { "ApproximateFirstReceiveTimestamp": "1442428276921", "SenderId": "AIDAIAZKMSNQ7TEXAMPLE", "ApproximateReceiveCount": "5", "SentTimestamp": "1442428276921" }, "MessageAttributes": { "PostalCode": { "DataType": "String", "StringValue": "ABC123" }, "City": { "DataType": "String", "StringValue": "Any City" } } } ] }

Contoh ini menerima pesan berikutnya yang tersedia, hanya mengembalikan SentTimestamp atribut SenderId dan serta atribut PostalCode pesan.

Perintah:

aws sqs receive-message --queue-url https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue --attribute-names SenderId SentTimestamp --message-attribute-names PostalCode

Output:

{ "Messages": [ { "Body": "My first message.", "ReceiptHandle": "AQEB6nR4...HzlvZQ==", "MD5OfBody": "1000f835...a35411fa", "MD5OfMessageAttributes": "b8e89563...e088e74f", "MessageId": "d6790f8d-d575-4f01-bc51-40122EXAMPLE", "Attributes": { "SenderId": "AIDAIAZKMSNQ7TEXAMPLE", "SentTimestamp": "1442428276921" }, "MessageAttributes": { "PostalCode": { "DataType": "String", "StringValue": "ABC123" } } } ] }
  • Untuk detail API, lihat ReceiveMessagedi Referensi AWS CLI Perintah.

Go
SDK untuk Go V2
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di AWS Repositori Contoh Kode.

// SqsActions encapsulates the Amazon Simple Queue Service (Amazon SQS) actions // used in the examples. type SqsActions struct { SqsClient *sqs.Client } // GetMessages uses the ReceiveMessage action to get messages from an Amazon SQS queue. func (actor SqsActions) GetMessages(queueUrl string, maxMessages int32, waitTime int32) ([]types.Message, error) { var messages []types.Message result, err := actor.SqsClient.ReceiveMessage(context.TODO(), &sqs.ReceiveMessageInput{ QueueUrl: aws.String(queueUrl), MaxNumberOfMessages: maxMessages, WaitTimeSeconds: waitTime, }) if err != nil { log.Printf("Couldn't get messages from queue %v. Here's why: %v\n", queueUrl, err) } else { messages = result.Messages } return messages, err }
  • Untuk detail API, lihat ReceiveMessagedi Referensi AWS SDK for Go API.

Java
SDK untuk Java 2.x
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di AWS Repositori Contoh Kode.

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;
  • Untuk detail API, lihat ReceiveMessagedi Referensi AWS SDK for Java 2.x API.

JavaScript
SDK untuk JavaScript (v3)
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di AWS Repositori Contoh Kode.

Menerima pesan dari antrian Amazon SQS.

import { ReceiveMessageCommand, DeleteMessageCommand, SQSClient, DeleteMessageBatchCommand, } from "@aws-sdk/client-sqs"; const client = new SQSClient({}); const SQS_QUEUE_URL = "queue_url"; const receiveMessage = (queueUrl) => client.send( new ReceiveMessageCommand({ AttributeNames: ["SentTimestamp"], MaxNumberOfMessages: 10, MessageAttributeNames: ["All"], QueueUrl: queueUrl, WaitTimeSeconds: 20, VisibilityTimeout: 20, }), ); export const main = async (queueUrl = SQS_QUEUE_URL) => { const { Messages } = await receiveMessage(queueUrl); if (!Messages) { return; } if (Messages.length === 1) { console.log(Messages[0].Body); await client.send( new DeleteMessageCommand({ QueueUrl: queueUrl, ReceiptHandle: Messages[0].ReceiptHandle, }), ); } else { await client.send( new DeleteMessageBatchCommand({ QueueUrl: queueUrl, Entries: Messages.map((message) => ({ Id: message.MessageId, ReceiptHandle: message.ReceiptHandle, })), }), ); } };

Menerima pesan dari antrian Amazon SQS menggunakan dukungan polling panjang.

import { ReceiveMessageCommand, SQSClient } from "@aws-sdk/client-sqs"; const client = new SQSClient({}); const SQS_QUEUE_URL = "queue-url"; export const main = async (queueUrl = SQS_QUEUE_URL) => { const command = new ReceiveMessageCommand({ AttributeNames: ["SentTimestamp"], MaxNumberOfMessages: 1, MessageAttributeNames: ["All"], QueueUrl: queueUrl, // The duration (in seconds) for which the call waits for a message // to arrive in the queue before returning. If a message is available, // the call returns sooner than WaitTimeSeconds. If no messages are // available and the wait time expires, the call returns successfully // with an empty list of messages. // https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_ReceiveMessage.html#API_ReceiveMessage_RequestSyntax WaitTimeSeconds: 20, }); const response = await client.send(command); console.log(response); return response; };
  • Untuk detail API, lihat ReceiveMessagedi Referensi AWS SDK for JavaScript API.

SDK untuk JavaScript (v2)
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di AWS Repositori Contoh Kode.

Menerima pesan dari antrian Amazon SQS menggunakan dukungan polling panjang.

// 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 queueURL = "SQS_QUEUE_URL"; var params = { AttributeNames: ["SentTimestamp"], MaxNumberOfMessages: 1, MessageAttributeNames: ["All"], QueueUrl: queueURL, WaitTimeSeconds: 20, }; sqs.receiveMessage(params, function (err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data); } });
Kotlin
SDK untuk Kotlin
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di AWS Repositori Contoh Kode.

suspend fun receiveMessages(queueUrlVal: String?) { println("Retrieving messages from $queueUrlVal") val receiveMessageRequest = ReceiveMessageRequest { queueUrl = queueUrlVal maxNumberOfMessages = 5 } SqsClient { region = "us-east-1" }.use { sqsClient -> val response = sqsClient.receiveMessage(receiveMessageRequest) response.messages?.forEach { message -> println(message.body) } } }
  • Untuk detail API, lihat ReceiveMessagedi AWS SDK untuk referensi API Kotlin.

PowerShell
Alat untuk PowerShell

Contoh 1: Contoh ini mencantumkan informasi hingga 10 pesan berikutnya yang akan diterima untuk antrian yang ditentukan. Informasi akan berisi nilai untuk atribut pesan yang ditentukan, jika ada.

Receive-SQSMessage -AttributeName SenderId, SentTimestamp -MessageAttributeName StudentName, StudentGrade -MessageCount 10 -QueueUrl https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue

Output:

Attributes : {[SenderId, AIDAIAZKMSNQ7TEXAMPLE], [SentTimestamp, 1451495923744]} Body : Information about John Doe's grade. MD5OfBody : ea572796e3c231f974fe75d89EXAMPLE MD5OfMessageAttributes : 48c1ee811f0fe7c4e88fbe0f5EXAMPLE MessageAttributes : {[StudentGrade, Amazon.SQS.Model.MessageAttributeValue], [StudentName, Amazon.SQS.Model.MessageAttributeValue]} MessageId : 53828c4b-631b-469b-8833-c093cEXAMPLE ReceiptHandle : AQEBpfGp...20Q5cg==
  • Untuk detail API, lihat ReceiveMessagedi Referensi AWS Tools for PowerShell Cmdlet.

Python
SDK untuk Python (Boto3)
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di AWS Repositori Contoh Kode.

def receive_messages(queue, max_number, wait_time): """ Receive a batch of messages in a single request from an SQS queue. :param queue: The queue from which to receive messages. :param max_number: The maximum number of messages to receive. The actual number of messages received might be less. :param wait_time: The maximum time to wait (in seconds) before returning. When this number is greater than zero, long polling is used. This can result in reduced costs and fewer false empty responses. :return: The list of Message objects received. These each contain the body of the message and metadata and custom attributes. """ try: messages = queue.receive_messages( MessageAttributeNames=["All"], MaxNumberOfMessages=max_number, WaitTimeSeconds=wait_time, ) for msg in messages: logger.info("Received message: %s: %s", msg.message_id, msg.body) except ClientError as error: logger.exception("Couldn't receive messages from queue: %s", queue) raise error else: return messages
  • Untuk detail API, lihat ReceiveMessagedi AWS SDK for Python (Boto3) Referensi API.

Ruby
SDK untuk Ruby
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di AWS Repositori Contoh Kode.

require "aws-sdk-sqs" require "aws-sdk-sts" # Receives messages in a queue in Amazon Simple Queue Service (Amazon SQS). # # @param sqs_client [Aws::SQS::Client] An initialized Amazon SQS client. # @param queue_url [String] The URL of the queue. # @param max_number_of_messages [Integer] The maximum number of messages # to receive. This number must be 10 or less. The default is 10. # @example # receive_messages( # Aws::SQS::Client.new(region: 'us-west-2'), # 'https://sqs.us-west-2.amazonaws.com/111111111111/my-queue', # 10 # ) def receive_messages(sqs_client, queue_url, max_number_of_messages = 10) if max_number_of_messages > 10 puts "Maximum number of messages to receive must be 10 or less. " \ "Stopping program." return end response = sqs_client.receive_message( queue_url: queue_url, max_number_of_messages: max_number_of_messages ) if response.messages.count.zero? puts "No messages to receive, or all messages have already " \ "been previously received." return end response.messages.each do |message| puts "-" * 20 puts "Message body: #{message.body}" puts "Message ID: #{message.message_id}" end rescue StandardError => e puts "Error receiving messages: #{e.message}" 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" max_number_of_messages = 10 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 "Receiving messages from queue '#{queue_name}'..." receive_messages(sqs_client, queue_url, max_number_of_messages) end # Example usage: run_me if $PROGRAM_NAME == __FILE__
  • Untuk detail API, lihat ReceiveMessagedi Referensi AWS SDK for Ruby API.

Rust
SDK untuk Rust
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di AWS Repositori Contoh Kode.

async fn receive(client: &Client, queue_url: &String) -> Result<(), Error> { let rcv_message_output = client.receive_message().queue_url(queue_url).send().await?; println!("Messages from queue with url: {}", queue_url); for message in rcv_message_output.messages.unwrap_or_default() { println!("Got the message: {:#?}", message); } Ok(()) }
  • Untuk detail API, lihat ReceiveMessagereferensi AWS SDK for Rust API.

SAP ABAP
SDK untuk SAP ABAP
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di AWS Repositori Contoh Kode.

Menerima pesan dari antrian Amazon SQS.

TRY. oo_result = lo_sqs->receivemessage( iv_queueurl = iv_queue_url ). " oo_result is returned for testing purposes. " DATA(lt_messages) = oo_result->get_messages( ). MESSAGE 'Message received from SQS queue.' TYPE 'I'. CATCH /aws1/cx_sqsoverlimit. MESSAGE 'Maximum number of in-flight messages reached.' TYPE 'E'. ENDTRY.

Menerima pesan dari antrian Amazon SQS menggunakan dukungan polling panjang.

TRY. oo_result = lo_sqs->receivemessage( " oo_result is returned for testing purposes. " iv_queueurl = iv_queue_url iv_waittimeseconds = iv_wait_time " Time in seconds for long polling, such as how long the call waits for a message to arrive in the queue before returning. " ). DATA(lt_messages) = oo_result->get_messages( ). MESSAGE 'Message received from SQS queue.' TYPE 'I'. CATCH /aws1/cx_sqsoverlimit. MESSAGE 'Maximum number of in-flight messages reached.' TYPE 'E'. ENDTRY.
  • Untuk detail API, lihat ReceiveMessagedi AWS SDK untuk referensi SAP ABAP API.