本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
使用 Ruby SDK 的亚马逊SQS示例
以下代码示例向您展示如何在 Amazon 中使用来执行操作和实现常见场景SQS。 AWS SDK for Ruby
操作是大型程序的代码摘录,必须在上下文中运行。您可以通过操作了解如何调用单个服务函数,还可以通过函数相关场景的上下文查看操作。
每个示例都包含一个指向完整源代码的链接,您可以在其中找到有关如何在上下文中设置和运行代码的说明。
操作
以下代码示例显示了如何使用ChangeMessageVisibility
。
- SDK对于 Ruby
-
注意
还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 require 'aws-sdk-sqs' # v2: require 'aws-sdk' # Replace us-west-2 with the AWS Region you're using for Amazon SQS. sqs = Aws::SQS::Client.new(region: 'us-west-2') begin queue_name = 'my-queue' queue_url = sqs.get_queue_url(queue_name: queue_name).queue_url # Receive up to 10 messages receive_message_result_before = sqs.receive_message({ queue_url: queue_url, max_number_of_messages: 10 }) puts "Before attempting to change message visibility timeout: received #{receive_message_result_before.messages.count} message(s)." receive_message_result_before.messages.each do |message| sqs.change_message_visibility({ queue_url: queue_url, receipt_handle: message.receipt_handle, visibility_timeout: 30 # This message will not be visible for 30 seconds after first receipt. }) end # Try to retrieve the original messages after setting their visibility timeout. receive_message_result_after = sqs.receive_message({ queue_url: queue_url, max_number_of_messages: 10 }) puts "\nAfter attempting to change message visibility timeout: received #{receive_message_result_after.messages.count} message(s)." rescue Aws::SQS::Errors::NonExistentQueue puts "Cannot receive messages for a queue named '#{queue_name}', as it does not exist." end
-
有关API详细信息,请参阅 “AWS SDK for Ruby API参考 ChangeMessageVisibility” 中的。
-
以下代码示例显示了如何使用CreateQueue
。
- SDK对于 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 # Example usage: run_me if $PROGRAM_NAME == __FILE__
-
有关API详细信息,请参阅 “AWS SDK for Ruby API参考 CreateQueue” 中的。
-
以下代码示例显示了如何使用DeleteQueue
。
- SDK对于 Ruby
-
注意
还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 require 'aws-sdk-sqs' # v2: require 'aws-sdk' # Replace us-west-2 with the AWS Region you're using for Amazon SQS. sqs = Aws::SQS::Client.new(region: 'us-west-2') sqs.delete_queue(queue_url: URL)
-
有关API详细信息,请参阅 “AWS SDK for Ruby API参考 DeleteQueue” 中的。
-
以下代码示例显示了如何使用ListQueues
。
- SDK对于 Ruby
-
注意
还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 require 'aws-sdk-sqs' require 'aws-sdk-sts' # @param sqs_client [Aws::SQS::Client] An initialized Amazon SQS client. # @example # list_queue_urls(Aws::SQS::Client.new(region: 'us-west-2')) def list_queue_urls(sqs_client) queues = sqs_client.list_queues queues.queue_urls.each do |url| puts url end rescue StandardError => e puts "Error listing queue URLs: #{e.message}" end # Lists the attributes of 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. # @example # list_queue_attributes( # Aws::SQS::Client.new(region: 'us-west-2'), # 'https://sqs.us-west-2.amazonaws.com/111111111111/my-queue' # ) def list_queue_attributes(sqs_client, queue_url) attributes = sqs_client.get_queue_attributes( queue_url: queue_url, attribute_names: ['All'] ) attributes.attributes.each do |key, value| puts "#{key}: #{value}" end rescue StandardError => e puts "Error getting queue attributes: #{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' sqs_client = Aws::SQS::Client.new(region: region) puts 'Listing available queue URLs...' list_queue_urls(sqs_client) 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}" puts "\nGetting information about queue '#{queue_name}'..." list_queue_attributes(sqs_client, queue_url) end
-
有关API详细信息,请参阅 “AWS SDK for Ruby API参考 ListQueues” 中的。
-
以下代码示例显示了如何使用ReceiveMessage
。
- SDK对于 Ruby
-
注意
还有更多相关信息 GitHub。查找完整示例,学习如何在 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__
-
有关API详细信息,请参阅 “AWS SDK for Ruby API参考 ReceiveMessage” 中的。
-
以下代码示例显示了如何使用SendMessage
。
- SDK对于 Ruby
-
注意
还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 require 'aws-sdk-sqs' require 'aws-sdk-sts' # @param sqs_client [Aws::SQS::Client] An initialized Amazon SQS client. # @param queue_url [String] The URL of the queue. # @param message_body [String] The contents of the message to be sent. # @return [Boolean] true if the message was sent; otherwise, false. # @example # exit 1 unless message_sent?( # Aws::SQS::Client.new(region: 'us-west-2'), # 'https://sqs.us-west-2.amazonaws.com/111111111111/my-queue', # 'This is my message.' # ) def message_sent?(sqs_client, queue_url, message_body) sqs_client.send_message( queue_url: queue_url, message_body: message_body ) true rescue StandardError => e puts "Error sending message: #{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' message_body = 'This is my message.' 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 "Sending a message to the queue named '#{queue_name}'..." if message_sent?(sqs_client, queue_url, message_body) puts 'Message sent.' else puts 'Message not sent.' end end # Example usage: run_me if $PROGRAM_NAME == __FILE__
-
有关API详细信息,请参阅 “AWS SDK for Ruby API参考 SendMessage” 中的。
-
以下代码示例显示了如何使用SendMessageBatch
。
- SDK对于 Ruby
-
注意
还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 require 'aws-sdk-sqs' require 'aws-sdk-sts' # # @param sqs_client [Aws::SQS::Client] An initialized Amazon SQS client. # @param queue_url [String] The URL of the queue. # @param entries [Hash] The contents of the messages to be sent, # in the correct format. # @return [Boolean] true if the messages were sent; otherwise, false. # @example # exit 1 unless messages_sent?( # Aws::SQS::Client.new(region: 'us-west-2'), # 'https://sqs.us-west-2.amazonaws.com/111111111111/my-queue', # [ # { # id: 'Message1', # message_body: 'This is the first message.' # }, # { # id: 'Message2', # message_body: 'This is the second message.' # } # ] # ) def messages_sent?(sqs_client, queue_url, entries) sqs_client.send_message_batch( queue_url: queue_url, entries: entries ) true rescue StandardError => e puts "Error sending messages: #{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' entries = [ { id: 'Message1', message_body: 'This is the first message.' }, { id: 'Message2', message_body: 'This is the second message.' } ] 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 "Sending messages to the queue named '#{queue_name}'..." if messages_sent?(sqs_client, queue_url, entries) puts 'Messages sent.' else puts 'Messages not sent.' end end
-
有关API详细信息,请参阅 “AWS SDK for Ruby API参考 SendMessageBatch” 中的。
-
无服务器示例
以下代码示例说明如何实现一个 Lambda 函数,该函数接收通过从队列接收消息而触发的事件。SQS该函数从事件参数检索消息并记录每条消息的内容。
- SDK对于 Ruby
-
注意
还有更多相关信息 GitHub。在无服务器示例
存储库中查找完整示例,并了解如何进行设置和运行。 使用 Ruby 在 Lambda 上使用SQS事件。
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 def lambda_handler(event:, context:) event['Records'].each do |message| process_message(message) end puts "done" end def process_message(message) begin puts "Processed message #{message['body']}" # TODO: Do interesting work based on the new message rescue StandardError => err puts "An error occurred" raise err end end
以下代码示例说明如何为从队列接收事件的 Lambda 函数实现部分批量响应。SQS该函数在响应中报告批处理项目失败,并指示 Lambda 稍后重试这些消息。
- SDK对于 Ruby
-
注意
还有更多相关信息 GitHub。在无服务器示例
存储库中查找完整示例,并了解如何进行设置和运行。 使用 Ruby 使用 Lambda 报告SQS批处理项目失败。
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 require 'json' def lambda_handler(event:, context:) if event batch_item_failures = [] sqs_batch_response = {} event["Records"].each do |record| begin # process message rescue StandardError => e batch_item_failures << {"itemIdentifier" => record['messageId']} end end sqs_batch_response["batchItemFailures"] = batch_item_failures return sqs_batch_response end end