如何使用 Sidekiq 和 httparty 为获取请求创建后台作业?

How to create a background job for get request with Sidekiq and httparty?

对于这种情况,我需要帮助开发一个带有 sidekiq 的 worker:

我有一个像这样的助手:

module UploadsHelper

    def save_image
        response = HTTParty.get(ENV['IMAGE_URI'])
        image_data = JSON.parse(response.body)
        images = image_data["rows"].map do |line|
            u = Image.new
            u.description = line[5]
            u.image_url = line[6]
            u.save
            u
        end
        images.select(&:persisted?)
    end

end

在我的 app/views/uploads/index.html.erb 中,我只是这样做

<% save_image %>

现在,当用户访问 uploads/index 页面时,图像会保存到数据库中。

问题是 API 的获取请求真的很慢。我想通过将其移动到带有 sidekiq 的后台作业来防止请求超时。

这是我的workers/api_worker.rb

class ApiWorker
  include Sidekiq::Worker

  def perform

  end

end

我只是不知道从这里开始的最佳方式。

使用 Sidekiq worker 执行此任务意味着该任务将 运行 异步,因此,它将无法立即 return 响应,该响应由 images.select(&:persisted?).

首先,不是调用save_image,而是调用worker的perform_async方法。

<% ApiWorker.perform_async %>

这将在 Sidekiq 的队列中加入一个作业(在本例中为 your_queue)。然后在worker的perform方法中,调用UploadsHelpersave_image方法。

class ApiWorker
  include Sidekiq::Worker
  sidekiq_options queue: 'your_queue'
  include UploadsHelper

  def perform
    save_image
  end
end

您可能想将 save_image 的回复保存在某处。要让 Sidekiq 开始处理作业,您可以从您的应用程序目录 运行 bundle exec sidekiq