Resque:按用户顺序执行的时间关键作业

lac*_*cco 5 queue ruby-on-rails resque

我的应用程序创建必须按用户顺序处理的resque作业,并且应尽可能快地处理它们(最大延迟1秒).

例如:为user1创建job1和job2,为user2创建job3.Resque可以并行处理job1和job3,但是应该按顺序处理job1和job2.

我对解决方案有不同的看法:

  • 我可以使用不同的队列(例如queue_1 ... queue_10)并为每个队列启动一个worker(例如rake resque:work QUEUE=queue_1).用户在运行时被分配给队列/工作人员(例如,登录,每天等)
  • 我可以使用动态"用户队列"(例如queue _#{user.id})并尝试扩展resque,一次只有1个worker可以处理队列(如Resque中所述:每个队列一个worker)
  • 我可以将作业放在非resque队列中,并使用"每用户元作业"和resque-lock(https://github.com/defunkt/resque-lock)来处理这些作业.

您是否在实践中遇到过其中一种情况?或者还有其他可能值得思考的想法吗?我很感激任何意见,谢谢!

lac*_*cco 5

感谢@Isotope的回答,我终于找到了一个似乎有效的解决方案(使用resque-retry和redis中的锁:

class MyJob
  extend Resque::Plugins::Retry

  # directly enqueue job when lock occurred
  @retry_delay = 0 
  # we don't need the limit because sometimes the lock should be cleared
  @retry_limit = 10000 
  # just catch lock timeouts
  @retry_exceptions = [Redis::Lock::LockTimeout]

  def self.perform(user_id, ...)
    # Lock the job for given user. 
    # If there is already another job for the user in progress, 
    # Redis::Lock::LockTimeout is raised and the job is requeued.
    Redis::Lock.new("my_job.user##{user_id}", 
      :expiration => 1, 
      # We don't want to wait for the lock, just requeue the job as fast as possible
      :timeout => 0.1
    ).lock do
      # do your stuff here ...
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

我在这里使用来自https://github.com/nateware/redis-objects的 Redis :: Lock (它封装了来自http://redis.io/commands/setex的模式).