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 )来处理这些作业。

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

感谢@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 

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

我之前做过这个。

确保顺序执行此类操作的最佳解决方案是将job1结束为job2排队。 job1和job2可以进入相同的队列或不同的队列,顺序无关紧要,这取决于你。

任何其他解决方案,例如同时排队job1 + 2但是告诉job2以0.5secs开始会导致竞争条件,因此不建议这样做。

有job1触发job2也很容易。

如果您想要另一个选项:我的最终建议是将两个作业捆绑到一个作业中,并添加一个参数,如果第二部分也应该被触发。

例如

 def my_job(id, etc, etc, do_job_two = false) ...job_1 stuff... if do_job_two ...job_2 stuff... end end