如何创建一个背景作业,以使用Sidekiq和Httparty获得请求



我需要在这种情况下开发与Sidekiq的工人:

我有一个看起来像这样的帮手:

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 %>

现在,当用户访问上传/索引页面时,图像将保存到数据库中。

问题在于,对API的GET请求确实很慢。我想通过将其转移到Sidekiq的后台工作来防止请求超时。

这是我的workers/api_worker.rb

class ApiWorker
  include Sidekiq::Worker
  def perform
  end
end

我只是不知道从这里继续前进的最佳方法。

使用Sidekiq Worker执行此任务意味着该任务将以异步运行,因此,它将无法立即返回响应,该响应由images.select(&:persisted?)发送。p>首先,您需要调用工人的perform_async方法。

<% ApiWorker.perform_async %>

这将在Sidekiq的队列中加入作业(在此示例中your_queue)。然后在Worker的perform方法中,调用save_image UploadsHelper的CC_8方法。

class ApiWorker
  include Sidekiq::Worker
  sidekiq_options queue: 'your_queue'
  include UploadsHelper
  def perform
    save_image
  end
end

您可能需要保存save_image的响应。要获得Sidekiq开始处理作业,您可以从应用程序目录运行bundle exec sidekiq

最新更新