使用 Sidekiq 进行 Active Job 并获取 ActiveJob::DeserializationError

2024-01-01

我正在尝试使用 Sidekiq 来运行以下作业。

该作业在未排队时执行良好 (perform_now),但在使用 Sidekiq 调用 (perform_later) 时失败。

AddEmployeesToRoomJob.perform_now room  ## works fine
AddEmployeesToRoomJob.perform_later room  ## breaks in Sidekiq

Error:

AddEmployeesToRoomJob JID-da24b13f405b1ece1212bbd5 INFO: fail: 0.003     sec
2016-08-20T14:57:16.645Z 19456 TID-owmym5fbk WARN:     {"class":"ActiveJob::QueueAdapters::SidekiqAdapter::JobWrapper","wrapped"    :"AddEmployeesToRoomJob","queue":"default","args":    [{"job_class":"AddEmployeesToRoomJob","job_id":"0ba5bd30-e281-49a7-a93f-    6e50445183ac","queue_name":"default","priority":null,"arguments":    [{"_aj_globalid":"gid://dragonfly/Room/1"}],"locale":"en"}],"retry":true,    "jid":"da24b13f405b1ece1212bbd5","created_at":1471704675.739077,"enqueued    _at":1471705036.6406531,"error_message":"Error while trying to     deserialize arguments: Couldn't find Room with     'id'=1","error_class":"ActiveJob::DeserializationError","failed_at":14717    04675.946183,"retry_count":4,"retried_at":1471705036.644416}
2016-08-20T14:57:16.645Z 19456 TID-owmym5fbk WARN:     ActiveJob::DeserializationError: Error while trying to deserialize     arguments: Couldn't find Room with 'id'=1
2016-08-20T14:57:16.645Z 19456 TID-owmym5fbk WARN:     /Users/tamlyn/.rvm/gems/ruby-2.2.3/gems/activerecord-    5.0.0.1/lib/active_record/relation/finder_methods.rb:357:in     `raise_record_not_found_exception!'

My Job类 AddEmployeesToRoomJob

  def perform(room)
    employees = Employee.all
    if employees.length > 0
      employees.each do |employee|
        UserRoom.create(user: employee, room: room)
      end
    end
  end
end

我的想法我不明白为什么它找不到我传递给执行方法的房间。就好像它在作业的排队/JSON化中以某种方式丢失了该变量?

Sidekiq 文档说

“不幸的是,这意味着如果在作业排队之后但在调用执行方法之前删除 [Room] 记录,则异常处理会有所不同。”

他们建议了一种解决方法,但我不知道这对我有什么帮助:

rescue_from ActiveJob::DeserializationError do |exception|
    # handle a deleted user record
end

预先感谢您的任何帮助!


我自己偶然发现了这个并找到了方法discard_on https://api.rubyonrails.org/v5.2.1/classes/ActiveJob/Exceptions/ClassMethods.html很有用。大多数情况下,没有必要对已删除或从未创建的记录执行作业。

Example:

class ApplicationJob < ActiveJob::Base
  discard_on ActiveJob::DeserializationError do |job, error|
    Rails.logger.error("Skipping job because of ActiveJob::DeserializationError (#{error.message})")
  end
end
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 Sidekiq 进行 Active Job 并获取 ActiveJob::DeserializationError 的相关文章

随机推荐