Sidekiq如何将参数传递给perform方法?

时间:2013-04-03 15:57:42

标签: ruby sidekiq

我有这个Sidekiq工人:

class DealNoteWorker
  include Sidekiq::Worker
  sidekiq_options queue: :email

  def perform(options = {})
    if options[:type] == "deal_watch_mailer"
      deal_watchers = DealWatcher.where("deal_id = ?", options[:deal_id])

      deal_note = DealNote.find(options[:deal_note_id])

      current_user = User.find(options[:current_user_id])

      deal_watchers.each do |deal_watcher|
        unless deal_watcher.user_id == options[:current_user_id]
          # Tell the DealWatchMailer to send emails to ALL watchers advising of change to deal
          if deal_watcher.user.active
            DealWatchMailer.deal_watch_email(deal_watcher, nil, deal_note, current_user, options[:url]).deliver
          end
        end
      end
    elsif options[:type] == "deal_note_mailer"
      options[:user_ids].each do |id|
        if DealWatcher.where("deal_id = ? and user_id =?", options[:deal_id], id).count == 0
          deal_note = Deal.find(options[:deal_note_id])
          user = User.find_by_id(id)
          DealNoteMailer.deal_note_email(deal_note, user, options[:url]).deliver
        end
      end
    end
  end
end

我将散列传递给perform_async方法,但我认为转移到perform方法的参数与传递给perform_async的参数类型不同。我尝试使用logger.infop来调试我的问题,但没有输出......

问题是作业已添加到电子邮件队列但从未得到处理。我甚至尝试在perform方法中引发异常(在方法的第一行)但是没有输出任何内容......

我知道以下工作人员的工作事实:

class DealNoteWorker
  include Sidekiq::Worker

  def perform(deal_id, deal_note_id, current_user_id, url)
    deal_watchers = DealWatcher.where("deal_id = ?", deal_id)

    deal_note = DealNote.find(deal_note_id)

    current_user = User.find(current_user_id)

    deal_watchers.each do |deal_watcher|
      unless deal_watcher.user_id == current_user_id
        # Tell the DealWatchMailer to send emails to ALL watchers advising of change to deal
        if deal_watcher.user.active
          DealWatchMailer.deal_watch_email(deal_watcher, nil, deal_note, current_user, url).deliver
        end
      end
    end
  end
end

所以问题在于hash参数(options)。我做错了什么?

2 个答案:

答案 0 :(得分:24)

来自Sidekiq documentation

  

传递给perform_async的参数必须由simple组成   JSON数据类型:字符串,整数,浮点数,布尔值,空值,数组和哈希值。   Sidekiq客户端API使用JSON.dump将数据发送到Redis。该   Sidekiq服务器从Redis中提取JSON数据并使用JSON.load   将数据转换回Ruby类型以传递给您的perform方法。   不要将符号或复杂的Ruby对象(如Date或Time!)传递为   那些将无法在转储/装载往返中幸存下来。

您可以在控制台上看到:

> options = { :a => 'b' }
> how_sidekiq_stores_the_options = JSON.dump(options)
> how_sidekiq_loads_the_options = JSON.load(how_sidekiq_stores_the_options)
> how_sidekiq_stores_the_options == how_sidekiq_loads_the_options
  false

看起来您正在使用符号作为options哈希的键。如果你切换到字符串键,它应该工作。

答案 1 :(得分:1)

您正在使用名为电子邮件的队列,因此您需要运行sidekiq -q电子邮件。