将对象传递给Sidekiq

时间:2014-05-13 08:03:33

标签: ruby-on-rails sidekiq

我尝试将一个小对象传递给sidekiq,但它将其转换为哈希值。此对象是mixpanel的跟踪对象。我也尝试在我的Worker中访问会话变量,但它们也没有。

思想?

控制器

MixpanelWorker.perform_async(@mixpanel, 'person', mixpanel_distinct_id, cleaned_params)

MixpanelWorker

  def perform(mixpanel_object, type_of_send, distinct_id, event)
    case type_of_send
    when 'person'
      mixpanel_object.people.set(distinct_id, event)
    when 'event'
      mixpanel_object.track(distinct_id, event)
    end
  end

3 个答案:

答案 0 :(得分:20)

答案 1 :(得分:9)

解决您要解决的问题的最佳方法是将对象数据保存在数据库中,然后将@mixpanel的ID传递给MixpanelWorker作业,如下所示:

@mixpanel = Mixpanel.create [your parameters]
MixpanelWorker.perform_async @mixpanel.id, 'person', mixpanel_distinct_id, cleaned_params

然后你的MixpanelWorker会像这样处理这个工作:

def perform(mixpanel_id, type_of_send, distinct_id, event)
  mixpanel_object = Mixpanel.find mixpanel_id

  case type_of_send
   when 'person'
     mixpanel_object.people.set(distinct_id, event)
   when 'event'
     mixpanel_object.track(distinct_id, event)
  end
end

另请阅读Mike Perham发布的链接,我想他可能对Sidekiq有所了解;)。

答案 2 :(得分:0)

如果您正在寻找默认情况下将对象传递给sidekiq作业而不需要更新每个作业的args的方式,则可以使用中间件方法。

Sidekiq提供客户端和服务器中间件:

  • 客户端中间件先运行自定义逻辑,然后再执行Redis中的工作
  • 服务器中间件在处理任何sidekiq作业之前运行

在下面的代码示例中,我们传递了current_user,但是它可以是任何请求特定的数据,例如请求trace_id

class SidekiqClientMiddleware
  def call(_worker_class, job, _queue, _redis_pool = nil)
    # Set current user login in job payload
    if Thread.current[:current_user].present?
      job['current_user'] = Thread.current[:current_user]
    end
    yield
  end
end

class SidekiqServerMiddleware
  def call(_worker, job, _queue)
    if job.key?('current_user')
      set_current_user(job['current_user'])
    end

    yield
  end

  private

  def set_current_user(current_user)
    Thread.current[:current_user] = current_user
  end
end

Sidekiq.configure_client do |config|
  config.client_middleware do |chain|
    chain.add SidekiqClientMiddleware
  end
end

Sidekiq.configure_server do |config|
  config.client_middleware do |chain|
    # sidekiq job can call another sidekiq job in which case
    # sidekiq server itself will act as the client
    chain.add SidekiqClientMiddleware
  end
  config.server_middleware do |chain|
    chain.add SidekiqServerMiddleware
  end
end

参考https://blog.bigbinary.com/2018/12/05/passing-current-user-by-default-in-sidekiq.html