Hay más AWS SDK ejemplos disponibles en el GitHub repositorio de AWS Doc SDK Examples
Las traducciones son generadas a través de traducción automática. En caso de conflicto entre la traducción y la version original de inglés, prevalecerá la version en inglés.
Utilícelo ReceiveMessage
con un o AWS SDK CLI
En los siguientes ejemplos de código se muestra cómo se utiliza ReceiveMessage
.
Los ejemplos de acciones son extractos de código de programas más grandes y deben ejecutarse en contexto. Puede ver esta acción en contexto en los siguientes ejemplos de código:
- .NET
-
- AWS SDK for .NET
-
nota
Hay más en marcha GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS
. Reciba mensajes de una cola utilizando suURL.
/// <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; }
Recibe un mensaje de una SQS cola de Amazon y, a continuación, borra el mensaje.
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; } }
-
Para API obtener más información, consulta la ReceiveMessagesección AWS SDK for .NET APIReferencia.
-
- C++
-
- SDKpara C++
-
nota
Hay más información GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS
. 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(); }
-
Para API obtener más información, consulte ReceiveMessagela AWS SDK for C++ APIReferencia.
-
- CLI
-
- AWS CLI
-
Recepción de un mensaje
En este ejemplo, se reciben hasta 10 mensajes disponibles y se devuelven todos los atributos disponibles.
Comando:
aws sqs receive-message --queue-url
https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue
--attribute-namesAll
--message-attribute-namesAll
--max-number-of-messages10
Salida:
{ "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" } } } ] }
En este ejemplo, se recibe el siguiente mensaje disponible y se devuelven solo los SentTimestamp atributos SenderId y, además, el atributo del PostalCode mensaje.
Comando:
aws sqs receive-message --queue-url
https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue
--attribute-namesSenderId
SentTimestamp
--message-attribute-namesPostalCode
Salida:
{ "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" } } } ] }
-
Para API obtener más información, consulte ReceiveMessage
la Referencia de AWS CLI comandos.
-
- Go
-
- SDKpara Go V2
-
nota
Hay más información GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de 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 } // GetMessages uses the ReceiveMessage action to get messages from an Amazon SQS queue. func (actor SqsActions) GetMessages(ctx context.Context, queueUrl string, maxMessages int32, waitTime int32) ([]types.Message, error) { var messages []types.Message result, err := actor.SqsClient.ReceiveMessage(ctx, &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 }
-
Para API obtener más información, consulte ReceiveMessage
la AWS SDK for Go APIReferencia.
-
- Java
-
- SDKpara Java 2.x
-
nota
Hay más información. GitHub Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS
. 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;
-
Para API obtener más información, consulte ReceiveMessagela AWS SDK for Java 2.x APIReferencia.
-
- JavaScript
-
- SDKpara JavaScript (v3)
-
nota
Hay más información. GitHub Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS
. Recibe un mensaje de una SQS cola de Amazon.
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, })), }), ); } };
Recibe un mensaje de una SQS cola de Amazon utilizando el soporte de encuestas largas.
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; };
-
Para API obtener más información, consulte ReceiveMessagela Referencia.AWS SDK for JavaScript API
-
- SDKpara JavaScript (v2)
-
nota
Hay más información GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS
. Recibe un mensaje de una SQS cola de Amazon utilizando el soporte de encuestas largas.
// 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); } });
-
Para obtener información, consulte la Guía para desarrolladores de AWS SDK for JavaScript.
-
Para API obtener más información, consulte ReceiveMessagela Referencia.AWS SDK for JavaScript API
-
- Kotlin
-
- SDKpara Kotlin
-
nota
Hay más información. GitHub Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS
. 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) } } }
-
Para API obtener más información, consulta ReceiveMessage
la AWS SDKAPIreferencia sobre Kotlin.
-
- PowerShell
-
- Herramientas para PowerShell
-
Ejemplo 1: En este ejemplo se muestra la información de hasta los 10 mensajes siguientes que se van a recibir en la cola especificada. La información contendrá valores para los atributos de mensaje especificados, si existen.
Receive-SQSMessage -AttributeName SenderId, SentTimestamp -MessageAttributeName StudentName, StudentGrade -MessageCount 10 -QueueUrl https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue
Salida:
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==
-
Para API obtener más información, consulte ReceiveMessage AWS Tools for PowerShellCmdlet Reference.
-
- Python
-
- SDKpara Python (Boto3)
-
nota
Hay más información. GitHub Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS
. 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
-
Para API obtener más información, consulte ReceiveMessagela AWS SDKreferencia de Python (Boto3). API
-
- Ruby
-
- SDKpara Ruby
-
nota
Hay más información GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS
. 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__
-
Para API obtener más información, consulte ReceiveMessagela AWS SDK for Ruby APIReferencia.
-
- Rust
-
- SDKpara Rust
-
nota
Hay más información GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS
. 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(()) }
-
Para API obtener más información, consulte ReceiveMessage
la APIreferencia AWS SDK de Rust.
-
- SAP ABAP
-
- SDKpara SAP ABAP
-
nota
Hay más información GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS
. Recibe un mensaje de una SQS cola de Amazon.
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.
Recibe un mensaje de una SQS cola de Amazon utilizando el soporte de encuestas largas.
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.
-
Para API obtener más información, consulta aquí como ReceiveMessagereferencia AWS SDK. SAP ABAP API
-