指定 Amazon SQS 中的消息可见性超时 - 适用于 Ruby 的 Amazon 开发工具包
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅中国的 Amazon Web Services 服务入门

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

指定 Amazon SQS 中的消息可见性超时

在 Amazon SQS 中,在收到消息后,消息将立即保留在队列中。为防止其他用户再次处理消息,Amazon SQS 会设置可见性超时。这是 Amazon SQS 阻止其他使用组件接收并处理消息的一段时间。要了解更多信息,请参阅可见性超时

在此示例中,您使用Amazon适 SDK for Ruby 与 Amazon SQS:

  1. 通过使用 Aws::SQS::Client#get_queue_url 来获取现有队列的 URL。

  2. 通过使用 Aws::SQS::Client#receive_message 来接收最多 10 个消息。

  3. 通过使用 Aws::SQS::Client#change_message_visibility 来指定在收到消息后消息不可见的时间间隔。

Prerequisites

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

您还需要创建队列我的队列,您可以在 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 specify the time interval during which messages to a queue are not visible after being received. require 'aws-sdk-sqs' # v2: require 'aws-sdk' sqs = Aws::SQS::Client.new(region: 'us-east-1') begin queue_name = "my-queue" queue_url = sqs.get_queue_url(queue_name: queue_name).queue_url receive_message_result_before = sqs.receive_message({ queue_url: queue_url, max_number_of_messages: 10 # Receive up to 10 messages, if there are that many. }) 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 '#{receive_queue_name}', as it does not exist." end