在 Amazon SQS 中发送和接收消息 - 适用于 Ruby 的 AWS 开发工具包
AWS 文档中描述的 AWS 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅中国的 AWS 服务入门

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

在 Amazon SQS 中发送和接收消息

在 Amazon SQS 中创建队列后,可以将消息发送到队列中,然后使用它。要了解更多信息,请参阅教程:。向 Amazon SQS 队列发送消息教程: 接收和删除来自 Amazon SQS 队列的消息

在此示例中,您结合使用AWS SDK for Ruby和 Amazon SQS 来:

  1. 通过使用 Aws::SQS::Client#send_message 来向队列发送消息。

注意

如果您的队列是 FIFO 队列,则除了 message_group_idid 参数外,还必须包括 message_body 参数。

  1. 通过使用 Aws::SQS::Client#receive_message 来接收队列中的消息。

  2. 显示有关消息的信息。

  3. 通过使用 Aws::SQS::Client#delete_message 来删除队列中的消息。

Prerequisites

在运行示例代码之前,您需要安装并配置AWS SDK for Ruby,如下所述:

您还需要创建队列 my-queue,您可以在 Amazon SQS 控制台中执行此操作。

Example

# 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