本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
在 Amazon SQS 中发送和接收消息
在 Amazon SQS 中创建队列后,您可以向其发送消息,然后使用它。要了解更多信息,请参阅教程:将消息发送到 Amazon SQS 队列和教程:从 Amazon SQS 队列接收和删除消息.
在此示例中,您使用Amazon使用Amazon SQS 的 SDK for Ruby 用于:
-
通过使用 Aws::SQS::Client#send_message 来向队列发送消息。
注意
如果您的队列是 FIFO 队列,则除了 message_group_id
和 id
参数外,还必须包括 message_body
参数。
-
通过使用 Aws::SQS::Client#receive_message 来接收队列中的消息。
-
显示有关消息的信息。
-
通过使用 Aws::SQS::Client#delete_message 来删除队列中的消息。
先决条件
在运行示例代码之前,您需要安装和配置AmazonSDK for Ruby,如中所述:
您可能还需要创建队列我的队,您可以在 Amazon SQS 控制台中执行此操作。
示例
# Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # This file is licensed under the Apache License, Version 2.0 (the "License"). # You may not use this file except in compliance with the License. A copy of the # License is located at # # http://aws.amazon.com/apache2.0/ # # This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS # OF ANY KIND, either express or implied. See the License for the specific # language governing permissions and limitations under the License. # Demonstrates how to: # 1. Send a message to a queue. # 2. Receive the message in the queue. # 3. Display information about the message. # 4. Delete the message from the queue. require 'aws-sdk-sqs' # v2: require 'aws-sdk' sqs = Aws::SQS::Client.new(region: 'us-east-1') # Send a message to a queue. queue_name = "my-queue" begin queue_url = sqs.get_queue_url(queue_name: queue_name).queue_url # Create a message with three custom attributes: Title, Author, and WeeksOn. send_message_result = sqs.send_message({ queue_url: queue_url, message_body: "Information about current NY Times fiction bestseller for week of 2016-12-11.", message_attributes: { "Title" => { string_value: "The Whistler", data_type: "String" }, "Author" => { string_value: "John Grisham", data_type: "String" }, "WeeksOn" => { string_value: "6", data_type: "Number" } } }) rescue Aws::SQS::Errors::NonExistentQueue puts "A queue named '#{queue_name}' does not exist." exit(false) end puts send_message_result.message_id # Receive the message in the queue. receive_message_result = sqs.receive_message({ queue_url: queue_url, message_attribute_names: ["All"], # Receive all custom attributes. max_number_of_messages: 1, # Receive at most one message. wait_time_seconds: 0 # Do not wait to check for the message. }) # Display information about the message. # Display the message's body and each custom attribute value. receive_message_result.messages.each do |message| puts message.body puts "Title: #{message.message_attributes["Title"]["string_value"]}" puts "Author: #{message.message_attributes["Author"]["string_value"]}" puts "WeeksOn: #{message.message_attributes["WeeksOn"]["string_value"]}" # Delete the message from the queue. sqs.delete_message({ queue_url: queue_url, receipt_handle: message.receipt_handle }) end