Ruby,AWS SQS:如何从队列中获取所有消息而不将其从队列中删除

时间:2017-11-24 19:28:46

标签: ruby amazon-sqs

如何下​​载SQS队列中的所有消息,但将它们保留在队列中。

我需要将其用于分析目的而不是实际执行消息,这是因为我需要在下载后将消息保留在队列中。

1 个答案:

答案 0 :(得分:3)

AWS API允许您从10个批次中下载队列中的消息。问题是,如果您多次请求消息,则可能会再次收到相同的消息。

诀窍是保持下载的消息对后续请求保持隐藏状态,直到您下载完所有消息为止。这会产生影响,例如,其他消费者也无法访问这些消息。

代码示例:

require "aws-sdk" # gem "aws-sdk", "~> 3"

client = Aws::SQS::Client.new(:region => "eu-west-1")
queue_url = "https://sqs.eu-west-1.amazonaws.com/XXXX/your_queueu"

queue =
  Aws::SQS::Queue.new({
    :url => queue_url,
    :client => client
  })

loop do
  # [Aws::SQS::Queue.receive_messages documentation](http://docs.aws.amazon.com/sdk-for-ruby/v3/api/Aws/SQS/Queue.html#receive_messages-instance_method)
  messages =
    queue.receive_messages({
      :max_number_of_messages => 10,
      :visibility_timeout => 10 # make this as big as necessary to give time to the script to get all the Messages
    })

  messages.each do |message|
    # [Aws::SQS::Message documentation](http://docs.aws.amazon.com/sdk-for-ruby/v3/api/Aws/SQS/Message.html)
    puts message.body # send the output to a file or where do you want
  end

  break if messages.length.zero?
end