如何在我的 rails 应用程序后台侦听 AWS SQS 消息?

How do I listen for AWS SQS messages in the background of my rails app?

我想在 rails 应用程序的后台异步轮询消息。 Shoryuken 不起作用,因为我希望我的 rails 应用程序也能侦听传入的 HTTP 请求。

config/initializers 中创建一个初始值设定项,如下所示:

# Allows the thread to crash our app for us
Thread.abort_on_exception = true
Thread.new do
    queue_url = "..."
    poller = Aws::SQS::QueuePoller.new(queue_url)
    poller.poll do |msg|
      puts msg.body
    end
end

您可以使用 Active Job 通过更复杂的作业处理消息:

像这样创建工作: rails g job process_a_message

然后在轮询块中:

    poller.poll do |msg|
      ProcessAMessageJob.perform_later msg.body
    end