1

这是我的Sidekiq设置:

调用我的后台进程的控制器

BackgroundStatCalculator.perform_async @game.athlete.id, @game.id, current_athlete_sport.id

Sidekiq 工人:

class BackgroundStatCalculator
  include Sidekiq::Worker

  def perform(user_id, game_id, sport_id)
    sport = Sport.find sport_id
    sport.stat_type_categories.each do |st_cat|
      calc = "StatCalculators::#{st_cat.name}".constantize.new(user_id, game_id)
      calc.run_calculations
    end
  end
end

计算器:

module StatCalculators
  class Passing
    def initialize(user_id, game_id)
      @user = User.find(user_id)
      @game = Game.find(game_id)
    end

    def save_completion_percentage
      completions = Stat.for_type("Completions").for_user(@user).sum(:float_value)
      attempts = Stat.for_type("Pass Attempts").for_user(@user).sum(:float_value)
      value = completions/attempts
      stat = Stat.new(value: value, game_id: @game.id, athlete_id: @user.id, float_value: value)
      stat.save(validate: false)
    end

    def run_calculations
      klass = self.class
      klass.instance_methods(false).each do |method|
        klass.instance_method(method).bind(self).call
      end
    end
  end
end

堆栈跟踪:

2013-06-07T17:55:34Z 73625 TID-ov6v51sww BackgroundStatCalculator JID-5bab7cec30523a4b12dd6438 INFO: fail: 5.155 sec
2013-06-07T17:55:34Z 73625 TID-ov6v51sww WARN: {"retry"=>true, "queue"=>"default", "class"=>"BackgroundStatCalculator", "args"=>[58, 68, 6], "jid"=>"5bab7cec30523a4b12dd6438", "error_message"=>"stack level too deep", "error_class"=>"SystemStackError", "failed_at"=>"2013-06-07T17:42:01Z", "retry_count"=>5, "retried_at"=>2013-06-07 17:55:34 UTC}
2013-06-07T17:55:34Z 73625 TID-ov6v51sww WARN: stack level too deep
2013-06-07T17:55:34Z 73625 TID-ov6v51sww WARN: /Users/dennismonsewicz/.rvm/gems/ruby-1.9.3-p429/gems/sidekiq-2.7.4/lib/sidekiq/processor.rb:88

出于某种原因,当.perform_async被调用时,它不仅执行一次就完成了……它会将 100 行转储到我的数据库中。

以前有人遇到过这个问题吗?我对与 Sidekiq 合作还很陌生,所以我为我的无知道歉

4

1 回答 1

2

您创建了一个无限循环的调用,导致堆栈溢出。

您的run_calculations方法调用它所在对象上的每个实例方法,其中包括run_calculations. 您需要从列表中过滤掉此方法,或者更好的是,找到一种方法将您要调用的计算方法列入白名单。也许使用像“calculate_”这样的前缀。

module StatCalculators
  class Passing
    def initialize(user_id, game_id)
      ...
    end

    def calculate_completion_percentage
       ...
    end

    def run_calculations
      klass = self.class
      calculation_methods = klass.instance_methods(false).select do |method|
         method.to_s.match /calculate_/
      end
      calculation_methods.each do |method|
        klass.instance_method(method).bind(self).call
      end
    end
  end
end
于 2013-08-06T15:04:43.350 回答