2013-04-03 36 views
12

我有這個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 

所以問題在於散列參數(選項)。請問我做錯了什麼?

+0

你確定你已經開始sidekiq工人?在另一個終端中運行'bundle exec sidekiq'。另外,你正在使用一個名爲'email'的隊列,所以你需要運行'sidekiq -q email'。 –

+0

是的,這是問題所在。我需要用電子郵件隊列啓動sidekiq。所以我在sidekiq.yml配置文件中添加了一個隊列列表,解決了這個問題。你可以添加你的評論作爲答案,以便我可以接受它嗎? –

回答

1

您正在使用一個名爲email的隊列,因此您需要運行sidekiq -q電子郵件。

19

Sidekiq documentation

傳遞給perform_async必須由簡單 JSON數據類型的參數:字符串,整數,浮點數,布爾值,null,數組和散列。 Sidekiq客戶端API使用JSON.dump將數據發送到Redis。Sidekiq服務器從Redis獲取JSON數據並將JSON.load用於 將數據轉換回Ruby類型以傳遞給執行方法。 不要將符號或複雜的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哈希鍵。如果你切換到字符串鍵,它應該工作。

+0

另請注意,哈希可能有問題。將這些作爲JSON傳遞給我解決了一個神祕的「錯誤數量的參數」錯誤。 – ericpeters0n

+0

我有類似的東西。工作人員第一次運行時,我得到了一個我的代碼引發的異常,下一次重試時出現錯誤的參數錯誤。 – holaSenor